I need some help or guide on how to download a form into a CSV file. What I'm trying to do here is :
<form>
<select name="mydropdown">
<option value="Chicken">Fresh Milk</option>
<option value="Apple">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>
</form>
<input type=button>
The GSP should be some what look like this and when the csv file is being downloaded, I'm not sure what the controller needs and the result should be one of the values in the options that is being selected and display it as text in the file. By the way I'm using grails. So is there anyone out there can help me with this? I've been researching on it and there isn't any result on this.
Thank you guys so much :)
You can use OpenCSV to do the work.
Define the dependency
dependencies {
...
compile('net.sf.opencsv:opencsv:2.0')
...
}
Create the action
def export() {
ByteArrayOutputStream output = new ByteArrayOutputStream()
char separator = ';'
CSVWriter writer = new CSVWriter(new OutputStreamWriter(output), separator);
def line = [params.mydropdown]
writer.writeNext(line as String[])
//use writeNext as many times as needed
writer.close()
byte[] bytes = output.toByteArray()
//needed to force download
response.setContentType("text/csv")
response.setContentLength(bytes.length)
response.setHeader("Content-Disposition", "attachment; filename=mycsv.csv")
response.outputStream << bytes
}
Change your form to go to export
<g:form action="export">
...
</g:form>