4

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 ();
}
}
}
1
  • Are you trying to import into Excel ? Commented Jul 2, 2010 at 18:44

2 Answers 2

6

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:

Sign up to request clarification or add additional context in comments.

1 Comment

How to invoke the CsvServlet? How exactly does the web.xml entry looks like?
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.