【问题标题】:Export to CSV file and open in browser导出为 CSV 文件并在浏览器中打开
【发布时间】:2012-10-20 14:29:32
【问题描述】:

我遇到了一个问题,我需要将数据导出到 .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 文件,但它是空的。我的数据没有填充到其中。 请提出我做错了什么。

【问题讨论】:

  • 在最后添加myWriter.flush();myWriter.close(); & 同时在屏幕上打印相同的数据System.out.println(EmployeeCode + "==" + Band); 看看你是否正在获取数据。
  • Fahim,是的,我正在使用 Sys 打印数据。
  • @user179516 我们应该在最后关闭文件写入器以从流中读取 :)
  • 你能在最后加上myWriter.flush();myWriter.close(); 告诉我你得到了什么吗?

标签: java csv export-to-csv


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多