So, I was just trying to solve the same problem - responding to a Grails 3 request with CSV download.
I got a tip from the Grails slack channel to use the Apache Commons CSV code, which takes care of details such as handling commas, quotes, and other special characters.
To use it, you need to add it depending on the project. In build.gradle , under dependencies add:
compile "org.apache.commons:commons-csv:1.2"
Here is an example of a controller that integrates everything and responds to all requests with CSV loading for the Item domain object.
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) } } } }
source share