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

发布于 2024-09-07 20:24:27 字数 1959 浏览 0 评论 0 原文

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

这是 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 ();
}
}
}

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 ?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

樱桃奶球 2024-09-14 20:24:27

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

  • 您需要将 CSV 写入 <代码>HttpServletResponse#getWriter()
  • 您需要将 Content-Disposition 标头设置为 attachment,以强制在网络浏览器中进行另存为对话框,最终连同文件名< /代码> 属性。有一个(主要?)警告:MSIE 浏览器不会使用指定的文件名作为另存为对话框中的实际文件名,而是使用URL 的路径信息。
  • 您需要将 Content-Type 标头设置为 text/csv 来指示网络浏览器它是什么类型的文件,以便当最终用户选择时它可以找到正确的关联应用程序打开而不是保存。通常,在 Windows 计算机上,MS Excel 默认与该内容类型关联。

为了实现这些要求,您需要创建一个 CsvServlet,它在 doGet() 方法中基本上执行以下操作。

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

就这样。顺便说一句,flush()close() 并不是严格必要的,但如果您想避免请求链中的其他内容向响应正文(这应该严格不会发生,但它只会将 IllegalStateException 和/或 IOException 发送到服务器日志中,而不是对然后

,将 web.xml 中的 CsvServlet 映射为 /csv/*url-pattern 并通过 http://example.com/context/csv/filename.csv 调用它 。


也就是说,您可能更喜欢一个真正的 CSV 格式化程序/编写器,它可以很好地写入 String[][]List> OutputStreamWriter,特此遵守 CSV 格式规则 如果字段值本身包含引号或逗号,则 CSV 格式将被破坏。

另请参阅:

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

  • You need to write the CSV to HttpServletResponse#getWriter().
  • You need to set Content-Disposition header to attachment to force a Save As dialogue in the webbrowser, eventually along with a filename attribute. There's one (major?) caveat: the MSIE browser won't use the specified filename as actual file name in the Save As dialogue, it will instead use the last part of the pathinfo of the URL.
  • You need to set Content-Type header to text/csv to instruct the webbrowser what kind of file it is so that it can find the correct associated application when the enduser chooses to Open instead of Save. Usually, on Windows Machines, MS Excel is by default associated with that content type.

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

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 not happen, but it would only emit IllegalStateExceptions and/or IOExceptions into the server logs instead of malforming the response.

Then, map the CsvServlet in web.xml with an url-pattern of /csv/* and invoke it by http://example.com/context/csv/filename.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 OutputStream or 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.

See also:

嘦怹 2024-09-14 20:24:27

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文