Using OpenCSV, I can successfully create a CSV file on disc, but what I really need is to allow users download the CSV with a download button, I don't need to save on disk, just download. Any ideas?
@GET
@Path("/downloadCsv")
public Object downloadCsv() {
CSVWriter writer;
FileWriter wr;
//Or should I use outputstream here?
wr= new FileWriter("MyFile.csv");
writer = new CSVWriter(wr,',');
for (Asset elem: assets) {
writer.writeNext(elem.toStringArray());
}
writer.close();
}
EDIT: I do NOT want to save/read file on disc EVER
Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).
There is no function in the API that will return results in CSV format. You will need to use language-level utilities to create a CSV file while generating the reports.
You can import data into a data source that is configured to receive CSV data by publishing CSV files through a REST service.
To force "save as", you need to set the content disposition HTTP header in the response. It should look like this:
Content-Disposition: attachment; filename="whatever.csv"
It looks like you're using JAX-RS. This question shows how to set the header. You can either write the CSV to the HTTP response stream and set the header there or return a Response
object like so:
return Response.ok(myCsvText).header("Content-Disposition", "attachment; filename=" + fileName).build();
You do not need to write to a File
object in the middle of this process so can avoid writing to disk.
First, you code cannot be compiled, right? Method downloadCsv()
declares return type Object
but does not return anything.
I'd change the declaration to String downloadCsv()
and return the content of CSV as string. To do this use StringWriter
instead of FileWriter
and then say return wr.toString()
.
The only thing that is missing here is content type. You annotate your method as @Produces({"text/csv"})
.
I think, that's it.
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