我遇到了一个问题,我需要将数据导出到 .csv 文件,但不将文件存储在文件系统中 - 相反,我只需要在浏览器中打开文件。
我编写了以下代码将数据写入 .csv 文件:
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");
我可以打开 .csv 文件,但它是空的。我的数据没有填充到其中。
请建议我做错了什么。
FileWriter
将内容写入output.csv
文件,不在响应输出流上。你应该做类似的事情:
OutputStream out = response.getOutputStream();
获取响应输出流。
并将内容写入out
流,类似:
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)