How to create csv file using servlet?

I want to load a csv file from servlet.Data from Object[] obj=search.getSearch();

I have object[] data, I need to write to csv and load.

Could you help me in the servlet class?

+3
java servlets csv
source share
4 answers

How can Object[] represent CSV data? Does it contain one row with several columns or several rows with one column? I would suggest that Object[][] or List<List<Object>> makes more sense.

In any case, you must adhere to the RFC4180 specification when creating the CSV file. It is basically simple, there are only 3 strict rules:

  • Fields are separated by a comma.
  • If the comma occurs inside the field, then the field must be surrounded by double quotation marks.
  • If a double quotation mark occurs inside a field, then the field must be surrounded by double quotation marks, and the double quotation mark inside the field must be escaped by another double quotation mark.

Here's a run example that does just that, based on List<List<T>> as the source and OutputStream as the destination.

 public static <T> void writeCsv (List<List<T>> csv, char separator, OutputStream output) throws IOException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8")); for (List<T> row : csv) { for (Iterator<T> iter = row.iterator(); iter.hasNext();) { String field = String.valueOf(iter.next()).replace("\"", "\"\""); if (field.indexOf(separator) > -1 || field.indexOf('"') > -1) { field = '"' + field + '"'; } writer.append(field); if (iter.hasNext()) { writer.append(separator); } } writer.newLine(); } writer.flush(); } 

Here you can use it in the servlet:

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<List<Object>> csv = getItSomehow(); response.setHeader("Content-Type", "text/csv"); response.setHeader("Content-Disposition", "attachment;filename=\"file.csv\""); writeCsv(csv, ';', response.getOutputStream()); } 

(note that in European locations instead of a semicolon for CSV files, a semicolon is used instead of a semicolon, do not hesitate to change)

Content-Disposition of attachment forces the Save As dialog. Note that MSIE has an incorrect behavior that does not accept filename as the default file name in the Save As dialog box, but instead occupies the last part of pathinfo. Therefore, if this servlet, for example, is called http://example.com/csv , you will get csv as the default file name. Rather, add it to pathinfo, as http://example.com/csv/file.csv follows. The servlet should only display on url-pattern /csv/* instead of /csv .

+11
source share

Here is an attempt:

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Other stuff you know that I don't.. Object[] data = search.getSearch(); response.setContentType("text/csv"); PrintWriter out = response.getWriter(); for (Object d : data) { out.println(d.field1 + "," + d.field2 + "," + d.field3 + ...); } } 

This is broken if your fields have a comma for the data. I leave you to figure out how to do this, since this is a quick Google Search .

+1
source share

There is JavaCSV to help you generate a csv view.

Then you can write the file using:

  • response.getWriter() to print content
  • response.setContentType("text/csv")
+1
source share

Here is some (edited for brevity and generality) code from the production servlet that I have running. This should be trivial for sharing in your specific dataset using the code below.

 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("application/octet-stream"); res.setHeader("Content-Disposition", "attachment; filename=\"TSR.csv\""); try { // Write the header line OutputStream o = res.getOutputStream(); String header = "ID,ControlNumber\n"; o.write(header.getBytes()); // Write the data lines Vector records = getRecords(); // Custom to my app Iterator i = records.iterator(); while (i.hasNext()) { // Custom data object; use your own StandardReportDTO sr = (StandardReportDTO) i.next(); StringBuffer line = new StringBuffer(); line.append(sr.getID()); line.append(","); line.append(sr.getControlNumber()); line.append("\n"); o.write(line.toString().getBytes()); o.flush(); } } catch (Exception e) { // log.error(e); } } 
0
source share

All Articles