Reputation: 3462
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?
Upvotes: 12
Views: 21727
Reputation: 7522
I guess it should be easy to build a CSV or any text file view. Here are suggested steps:
Create a View class (you can name it as CSVView
) extending org.springframework.web.servlet.view.AbstractView
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.
Upvotes: 21