Export to CSV file and open in browser

流过昼夜 提交于 2021-02-07 11:56:17

问题


I am stuck with an issue where I need to export data to a .csv file, but not store the file in file system - instead I need to simply open the file in browser.

I have written the below code to write data to .csv file:

FileWriter myWriter = new FileWriter("output.csv");
myWriter.append(EmployeeCode);
myWriter.append(',');
myWriter.append(Band);
myWriter.append('\n');
response.setHeader("Content-Disposition", "attachment; filename=output.csv"); 
response.setContentType("application/ms-excel"); 
response.setCharacterEncoding("UTF-8");

I am able to open a .csv file but it is empty. My data does not get populated into it. Please suggest what am I doing wrong.


回答1:


FileWriter writes the content in the output.csv file, not on the response output stream. You should do something like:

OutputStream out = response.getOutputStream();

To get the response output stream.

And write the content in the out stream, something like:

response.setContentType("application/ms-excel"); // or you can use text/csv
response.setHeader("Content-Disposition", "attachment; filename=output.csv"); 
try {
    // Write the header line
    OutputStream out = response.getOutputStream();
    String header = "EmployeeCode, Band\n";
    out.write(header.getBytes());
    // Write the content
    String line=new String(EmployeeCode+","+Band+"\n");
    out.write(line.toString().getBytes());
    out.flush();
} catch (Exception e) {
   log.error(e);
}


来源:https://stackoverflow.com/questions/13152738/export-to-csv-file-and-open-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!