导出为CSV文件并在浏览器中打开 [英] Export to CSV file and open in browser

查看:99
本文介绍了导出为CSV文件并在浏览器中打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,我需要将数据导出到.csv文件,而不是将文件存储在文件系统中-相反,我只需要在浏览器中打开文件即可.

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.

我编写了以下代码,将数据写入.csv文件:

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");

我能够打开.csv文件,但它为空.我的数据没有填充到其中.请提出我在做什么错.

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.

推荐答案

FileWriter 将内容写入 output.csv 文件中,而不是写入响应输出流中.您应该执行以下操作:

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

OutputStream out = response.getOutputStream();

获取响应输出流.

然后将内容写到 out 流中,例如:

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);
}

这篇关于导出为CSV文件并在浏览器中打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆