Create and download CSV file in a Java servlet
csv, download, java, servlets
Solution
I got the solution and I am posting it below.
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=\"userDirectory.csv\"");
try
{
OutputStream outputStream = response.getOutputStream();
String outputResult = "xxxx, yyyy, zzzz, aaaa, bbbb, ccccc, dddd, eeee, ffff, gggg\n";
outputStream.write(outputResult.getBytes());
outputStream.flush();
outputStream.close();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
Here we don't need to save / store the file in the server.
Thanks
Problem
I am working on Java ExtJS application in which I need to create and download a CSV file. - On clicking a button I want a CSV file to be downloaded to a client's machine. - On buttons listener I am calling a servlet using AJAX. There I am creating a CSV file. I don't want the CSV file to be saved in the server. I want the file should be created dynamically with a download option. I want the contents of a file to be created as a string and then I will serve the content as file in which it will open as download mode in browser (this I have achieved in other language, but not sure how to achieve it in Java). Here is my code only to create a CSV file, but I really don't want to create or save CSV file if I can only download the file as CSV. ``` public String createCSV() { try { String filename = "c:\\test.csv"; FileWriter fw = new FileWriter(filename); fw.append("XXXX"); fw.append(','); fw.append("YYYY"); fw.append(','); fw.append("ZZZZ"); fw.append(','); fw.append("AAAA"); fw.append(','); fw.append("BBBB"); fw.append('\n'); CSVResult.close(); return "Csv file Successfully created"; } catch(Exception e) { return e.toString(); } } ``` Can any one help me on this. Thanks