Java – how to create CSV files using servlets?
I want to download the CSV file from the servlet Data from object [] obj = search getSearch();
I have a data object [], I need to write to CSV and download it
Can you help me with my lessons?
Solution
How does object [] represent CSV data? Does it contain one row with multiple columns or multiple rows with one column? I imagine object [] [] or list < list < Object > > is more meaningful
In any case, you must follow rfc4180 spec when creating CSV files. It is basically very simple, with only three strict rules:
>Fields are separated by commas. > If a comma appears in a field, the field must be enclosed in double quotes. > If double quotation marks appear in a field, the field must be enclosed in double quotation marks, and the double quotation marks in the field must be escaped by another double quotation mark
This is a startup example, which performs this operation based on list < T > > As source and OutputStream as 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 is how to use it in a 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 European based locales use semicolons instead of commas for CSV files, please change them at any time)
Content – attachment handling will force save as dialog box Please note that MSIE has an error behavior. It does not save the file name as the default file name as the Save As dialog box, but it replaces the last part of pathinfo Therefore, if this servlet is http://example.com/csv Call, you will get CSV as the default file name Instead, attach it to pathinfo, as shown below http://example.com/csv/file.csv. The servlet should only be mapped to the URL pattern of / CSV / * instead of / CSV