简体   繁体   English

以grails格式呈现CSV格式

[英]Render in CSV format in grails

Grails provides Converter class to quickly transform any kind of Java/Groovy objects to either XML/JSON response. Grails提供了Converter类,可以将任何类型的Java / Groovy对象快速转换为XML / JSON响应。 Like, 喜欢,

render obj as XML

or 要么

render obj as JSON

I am working on a grails app that requires me to render an object in csv format. 我正在开发一个grails应用程序,它要求我以csv格式呈现对象。 Is there a way to do that? 有没有办法做到这一点?

I tried out few stuff and I have explained those below: 我尝试了一些东西,我已经解释了以下内容:

Snippet of my code 我的代码片段

csv {
    def results = []
    for(d in Data.list()) {
        def r= [d.id, d.name]
        results << r
    }
    def result = ''
    results.each{ row ->
        row.each{
            col -> result += col + ','
        }
        result = result[0..-2]
        result += '\n'
    }
    println result

    render(contentType:'text/csv',text:result)
}

I stored my results in an ArrayList and then converted them to a comma separated string and then passed it to a render method. 我将结果存储在ArrayList中,然后将它们转换为逗号分隔的字符串,然后将其传递给render方法。 When I run the above code on the browser, it creates the desired file and the browser pops up a dialog box to "Save As" the file. 当我在浏览器上运行上面的代码时,它会创建所需的文件,浏览器会弹出一个“另存为”文件的对话框。

When I changed the contentType to text/html, the file contents are displayed on the browser with no newline chars. 当我将contentType更改为text / html时,文件内容显示在浏览器上,没有换行符。

Is there a better way to render the contents of the csv file on the browser the same way its on the file. 有没有更好的方法在浏览器上以与文件相同的方式呈现csv文件的内容。

Thanks. 谢谢。

So I was just trying to solve the same problem -- responding to a Grails 3 request with a CSV download. 所以我只是试图解决同样的问题 - 使用CSV下载响应Grails 3请求。

I got a tip from the Grails slack channel to use the Apache Commons CSV code which takes care of the details like handling commas, quotes and other special characters. 我从Grails slack频道获得了一个提示,使用Apache Commons CSV代码来处理逗号,引号和其他特殊字符等细节。

To use it, you'll need to add it to your project's dependencies. 要使用它,您需要将它添加到项目的依赖项中。 In build.gradle , under dependencies add: build.gradle ,在dependencies项下添加:

compile "org.apache.commons:commons-csv:1.2"

Here's an example controller that puts everything together and responds to all requests with the CSV download for the domain object Item . 这是一个示例控制器,它将所有内容放在一起,并通过域对象Item的CSV下载响应所有请求。

package name.of.package

import grails.rest.*
import grails.converters.*
import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVPrinter

class ItemController extends RestfulController {

    static responseFormats = ['json', 'xml', 'csv']
    ItemController () {
        super(ApprovedHotel)
    }

    def export(Integer max) {

        def items = Item.list()
        withFormat {
            csv {
                def results = []
                for(d in items) {
                    def r= [d.column1, d.column2]
                    results << r
                }

                StringWriter stringWriter = new StringWriter();
                CSVPrinter printer = new CSVPrinter(stringWriter, CSVFormat.EXCEL);
                printer.printRecords( results )
                printer.flush()
                printer.close()
                result = stringWriter.toString()

                response.setHeader("Content-disposition", "attachment; filename=filename.csv")
                render(contentType:'text/csv',text:result)
            }
        }
    }
}

You can render the CSV as text/plain instead of text/html . 您可以将CSV呈现为text/plain而不是text/html Browsers will render this as plain text, similar to what you'd see if you open the file in an editor. 浏览器会将其呈现为纯文本,类似于在编辑器中打开文件时所看到的内容。

If you want to display csv data in the browser you need to use 如果要在浏览器中显示需要使用的csv数据

<br>

instead of \\n for a new line if you want new lines to be displayed properly in HTML. 如果您希望在HTML中正确显示新行,则代替\\ n表示新行。 Browsers generally ignore control characters and only base formatting on HTML tags. 浏览器通常忽略控制字符,仅忽略HTML标记上的基本格式。
If you want to allow the user to download a csv file code like the following will work. 如果要允许用户下载csv文件代码,则以下内容将起作用。

response.setHeader("Content-disposition", "attachment; filename=Edata.csv")
render(contentType: "text/csv", text:varContainingData )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM