gpt4 book ai didi

java - Grails函数生成的空Csv

转载 作者:行者123 更新时间:2023-12-02 15:43:03 25 4
gpt4 key购买 nike

我正在尝试在grails项目中使用apache commons csv生成一个csv文件。
那是代码:

def createAndDownloadExcelTuttiCampiRichiesta( ArrayList result ) {
def response = WebUtils.retrieveGrailsWebRequest().getCurrentResponse()
response.setContentType('application/CSV')
response.setHeader('Content-Disposition', 'Attachment;Filename="report.csv"')
try {
FileWriter fileWriter = new FileWriter(response.outputStream)
CSVPrinter csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withHeader("ID","Name","Designation","Company"))
csvPrinter.printRecord("1", "Test", "Test", "Test")
csvPrinter.printRecord("2", "Test", "Test", "Test")
csvPrinter.printRecord("3", "Test", "Test", "Test")
csvPrinter.printRecord("4", "Test", "Test", "Test")
csvPrinter.flush()
} catch(Exception e) {
log.error("Error parsing csv")
}
return
}

但它会生成一个空的csv文件。
为什么?

谢谢

最佳答案

具体细节可能会有所变化,具体取决于您喜欢的Grails版本,但是https://github.com/jeffbrown/francodecsv/tree/master/grails-app中的代码有效。启动应用程序,然后向http://localhost:8080/demo发送请求,该请求应下载如下所示的CSV文件...

$ cat ~/Downloads/report.csv
ID,Name,Designation,Company
1,Test,Test,Test
2,Test,Test,Test
3,Test,Test,Test
4,Test,Test,Test

https://github.com/jeffbrown/francodecsv/blob/master/grails-app/controllers/francodecsv/DemoController.groovy
package francodecsv

class DemoController {

DemoService demoService

def index() {
demoService.createAndDownloadExcelTuttiCampiRichiesta([])
}
}

https://github.com/jeffbrown/francodecsv/blob/master/grails-app/services/francodecsv/DemoService.groovy
package francodecsv

import grails.web.api.ServletAttributes
import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVPrinter

class DemoService implements ServletAttributes {

// result is ignored in this particular example... unclear from
// the StackOverflow question what that is supposed to be used for
void createAndDownloadExcelTuttiCampiRichiesta(ArrayList result) {
response.setContentType('application/CSV')
response.setHeader('Content-Disposition', 'Attachment;Filename="report.csv"')
CharArrayWriter writer = new CharArrayWriter()
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("ID", "Name", "Designation", "Company"))
csvPrinter.printRecord("1", "Test", "Test", "Test")
csvPrinter.printRecord("2", "Test", "Test", "Test")
csvPrinter.printRecord("3", "Test", "Test", "Test")
csvPrinter.printRecord("4", "Test", "Test", "Test")
csvPrinter.flush()
response.outputStream << writer.toCharArray()
}
}

希望对您有所帮助。

关于java - Grails函数生成的空Csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54674914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com