我正在尝试在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文件。 为什么?
谢谢
答案 0 :(得分:0)
具体细节可能会有所变化,具体取决于您喜欢的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
package francodecsv
class DemoController {
DemoService demoService
def index() {
demoService.createAndDownloadExcelTuttiCampiRichiesta([])
}
}
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()
}
}
我希望有帮助。