如何使用java servlet获取下载的csv文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3168272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:03:16  来源:igfitidea点击:

How to get download csv file using java servlet?

javaservletscsv

提问by Nancy

I have sample java servlet file.but it is export to local file.But i need to download the csv file when the hit download button ?

我有示例 java servlet 文件。但它导出到本地文件。但是我需要在点击下载按钮时下载 csv 文件?

here is servlet class , what code i need to add here for download the csv file ?

这是 servlet 类,我需要在此处添加什么代码才能下载 csv 文件?

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CsvFile extends HttpServlet { 
public void doGet (HttpServletRequest request,HttpServletResponse response) 
throws ServletException,IOException  {
try
{
      PrintWriter out = response.getWriter();
      String filename = "c:\csv\myfile.csv";
      FileWriter fw = new FileWriter(filename);

      fw.append("Employee Code");
      fw.append(',');
      fw.append("Employee Name");
      fw.append(',');
      fw.append("Employee Address");
      fw.append(',');
      fw.append("Employee Phone");
      fw.append(',');
      fw.append("Employee ZipCode");
      fw.append('\n');

      fw.append("E1");
      fw.append(',');
      fw.append("Vineet");
      fw.append(',');
      fw.append("Delhi");
      fw.append(',');
      fw.append("224277488");
      fw.append(',');
      fw.append("110085");
      fw.append('\n');

      fw.append("E2");
      fw.append(',');
      fw.append("Amar");
      fw.append(',');
      fw.append("Delhi");
      fw.append(',');
      fw.append("257765758");
      fw.append(',');
      fw.append("110001");
      fw.append('\n');

      fw.append("E3");
      fw.append(',');
      fw.append("Amit");
      fw.append(',');
      fw.append("Delhi");
      fw.append(',');
      fw.append("257685858");
      fw.append(',');
      fw.append("110005");
      fw.append('\n');

      fw.append("E4");
      fw.append(',');
      fw.append("Suman");
      fw.append(',');
      fw.append("Delhi");
      fw.append(',');
      fw.append("266447678");
      fw.append(',');
      fw.append("110081");
      fw.append('\n');


      fw.flush();
      fw.close();
      out.println("<b>Csv file Successfully created.</b>");

} 
catch (Exception ex) {
ex.printStackTrace ();
}
}
}

回答by Teja Kantamneni

Set content type to application/vnd.ms-exceland response header for content-disposition response.setHeader("Content-Disposition", "attachment; filename=\"myfile.csv\"");

将内容类型设置application/vnd.ms-excel为内容处理的响应标头 response.setHeader("Content-Disposition", "attachment; filename=\"myfile.csv\"");

回答by BalusC

You're writing to a file instead of to the HTTP response.

您正在写入文件而不是 HTTP 响应。

  • You need to write the CSV to HttpServletResponse#getWriter().
  • You need to set Content-Dispositionheader to attachmentto force a Save Asdialogue in the webbrowser, eventually along with a filenameattribute. There's one (major?) caveat: the MSIE browser won't use the specified filenameas actual file name in the Save Asdialogue, it will instead use the last part of the pathinfo of the URL.
  • You need to set Content-Typeheader to text/csvto instruct the webbrowser what kind of file it is so that it can find the correct associated application when the enduser chooses to Openinstead of Save. Usually, on Windows Machines, MS Excel is by default associated with that content type.
  • 您需要将 CSV 写入HttpServletResponse#getWriter().
  • 您需要将Content-Dispositionheader设置为在 webbrowser 中attachment强制另存为对话框,最终与一个filename属性一起。有一个(主要?)警告:MSIE 浏览器不会filename在“另存为”对话框中使用指定的实际文件名,而是使用 URL 路径信息的最后一部分。
  • 您需要将Content-Typeheader 设置text/csv为指示 webbrowser 它是什么类型的文件,以便当最终用户选择Open而不是Save时它可以找到正确的关联应用程序。通常,在 Windows 机器上,默认情况下 MS Excel 与该内容类型相关联。

To achieve those requirements, you need to create a CsvServletwhich does basically the following in the doGet()method.

要实现这些要求,您需要创建一个CsvServletdoGet()方法中基本上执行以下操作的方法。

String filename = request.getPathInfo().substring(1); // get rid of leading `/`
response.setHeader("Content-Type", "text/csv");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
PrintWriter writer = response.getWriter();
writer.append("CSV content");
// ...

That's all. The flush()and close()are by the way not strictly necessary, but useful if you want to avoid that something else further in the request chain is appending something to the response body (which should strictly nothappen, but it would only emit IllegalStateExceptions and/or IOExceptions into the server logs instead of malforming the response.

就这样。顺便说一下,flush()andclose()并不是绝对必要的,但是如果您想避免请求链中的其他内容将某些内容附加到响应正文中(这绝对应该发生,但它只会将IllegalStateExceptions 和/或IOExceptions 发送到服务器记录而不是使响应格式错误。

Then, map the CsvServletin web.xmlwith an url-patternof /csv/*and invoke it by http://example.com/context/csv/filename.csv.

然后,使用of映射CsvServletin并通过http://example.com/context/csv/filename.csv调用它。web.xmlurl-pattern/csv/*



That said, you'd probably rather like a real CSV formatter/writer which nicely writes a String[][]or a List<List<String>>to an OutputStreamor Writer, hereby respecting the CSV formatting rules. It might happen that a field value itself contains a quote or a comma, the CSV format would then break.

也就是说,您可能更喜欢真正的 CSV 格式化程序/编写器,它可以很好地将 aString[][]或 a写入List<List<String>>OutputStreamor Writer,从而遵守 CSV 格式规则。可能会发生字段值本身包含引号或逗号的情况,然后 CSV 格式会中断。

See also:

也可以看看: