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?

Piotr Nowicki
  • 17,914
  • 8
  • 63
  • 82
tsunade21
  • 3,442
  • 4
  • 25
  • 22
  • Spring doesn't provide CSV support. There are plenty CSV libraries for Java, though (just search for "java csv"). – skaffman Feb 01 '11 at 17:36

1 Answers1

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.

Community
  • 1
  • 1
Ritesh
  • 7,472
  • 2
  • 39
  • 43
  • 2
    an alternative solution can be found http://stackoverflow.com/questions/9913732/configuring-spring-mvc-controller-to-send-file-to-client, but it's a matter of taste. – Boris Treukhov Sep 17 '13 at 15:05