How to Return CSV Data in Browser From Spring Controller

Issue

Let say I have CSV data in a string and want to return it from a Spring controller. Imagine the data looks like this

a,b,c 
1,2,3
4,5,6

No matter what I have tried, the newlines come out as literally ‘\n’ in the response content, and if I double escape them as in “\n”, the response just contains the double backslashes too. In general, how to I return plain text data with newlines in it without the newlines being modified? I know how to return plain text, but still, the content comes with escaped newlines… This is what I current have (using Spring 3.0.5, not by choice)

@RequestMapping(value = "/api/foo.csv")
public ResponseEntity<String> fooAsCSV() {

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "text/plain; charset=utf-8");

    String data = "a,b,c\n1,2,3\n3,4,5";
    return new ResponseEntity<>(data, responseHeaders, HttpStatus.OK);
}

Which produces literally the string

"a,b,c\n1,2,3\n,3,4,5"

In the browser. How do I make it produce the correct data with new lines in tact as shown above?

Solution

You could write to the response directly using e.g.

@RequestMapping(value = "/api/foo.csv")
public void fooAsCSV(HttpServletResponse response) {         
    response.setContentType("text/plain; charset=utf-8");
    response.getWriter().print("a,b,c\n1,2,3\n3,4,5");
}

Since the return type is void and HttpServletResponse is declared as a method argument the request is assumed to be completed when this method returns.

Answered By – Bart

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published