Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 3 - export data in csv format

Tags:

spring

csv

I have some data in the DB and would like to be able to export it to a CSV file and provide a link so the user can download it.

Is there any mechanism provided by Spring 3 for this?

Do you know how could I do that?

like image 746
tsunade21 Avatar asked Feb 01 '11 17:02

tsunade21


People also ask

How do I export a dataset to csv?

Export data to a text file by saving itGo 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).


1 Answers

I guess it should be easy to build a CSV or any text file view. Here are suggested steps:

  1. Create a View class (you can name it as CSVView) extending org.springframework.web.servlet.view.AbstractView

  2. Override renderMergedOutputModel as follows (pseudo code):

BufferedWriter writer = new BufferedWriter(response.getWriter())

response.setHeader("Content-Disposition","attachment; filename=\"file.csv\"");

myDbData = (Whatever) modelMap.get("modelKey");

some kind of loop {writer.write(myDbData csv row); writer.newLine(); }

finally writer.flush(); writer.close();

After that just return ModelAndView with model (object Whatever with modelKey) and view as CSVView in the controller.

like image 166
Ritesh Avatar answered Jan 02 '23 23:01

Ritesh