I want to download a CSV file from a servlet. I have data in the array of objects (object[]
), I need to write it into CSV and download.
Could you help me how to do this in a servlet class?
How can Object[]
ever represent CSV data? Does it contain one row with several columns or several rows with one column? I'd imagine that Object[][]
or List<List<Object>>
makes more sense.
Anyway, when creating a CSV file you've to adhere the RFC4180 spec. It's basically simple, there are only 3 strict rules:
Here's a kickoff example which does exactly that based on a List<List<T>>
as source and an 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's how you can 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 Europe based locales use a semicolon instead of comma for CSV files, feel free to change)
The Content-Disposition
of attachment
will force a Save As dialogue. Note that MSIE has the misbehaviour that it doesn't take the filename
as default filename in the Save As dialogue, but it instead takes the last part of the pathinfo. So if this servlet is for example invoked by http://example.com/csv, then you'll get csv
as default filename. Rather append it to the pathinfo like follows http://example.com/csv/file.csv. The servlet should only be mapped on an url-pattern
of /csv/*
instead of /csv
.
Here's 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 broken if your fields have commas for data. I leave you to figure out how to do that since it's a quick Google Search.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With