12

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?

1
  • Spring doesn't provide CSV support. There are plenty CSV libraries for Java, though (just search for "java csv"). Commented Feb 1, 2011 at 17:36

1 Answer 1

21

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.

Sign up to request clarification or add additional context in comments.

1 Comment

an alternative solution can be found stackoverflow.com/questions/9913732/…, but it's a matter of taste.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.