Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get download csv file using java servlet?

Tags:

java

csv

servlets

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 ();
}
}
}
like image 217
Nancy Avatar asked Feb 27 '23 17:02

Nancy


2 Answers

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:

  • JSP page without HTML code for exporting data to Excel Sheet
like image 200
BalusC Avatar answered Mar 01 '23 06:03

BalusC


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

like image 45
Teja Kantamneni Avatar answered Mar 01 '23 05:03

Teja Kantamneni