Детали могут немного измениться в зависимости от того, какая версия 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()
}
}
Надеюсь, это поможет.