tags:

views:

30

answers:

2

Hi all,

I am trying to generate a csv file using a jsp file this its code:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%-- Set the content type --%>
<%@ page contentType="text/csv"%>

<c:forEach items="${chartData}" var="chartDataEntry" varStatus="status">
 ${chartDataEntry.date}, ${chartDataEntry.open}, ${chartDataEntry.high}, ${chartDataEntry.low}, ${chartDataEntry.close}, ${chartDataEntry.volume}
</c:forEach>

Its quite simple, and it works fine. The problem is that I need to insert a breakline after each row, but I can't get it working. I have tried with usuals: \n \r\n and so on.

Any ideas?

+1  A: 

In a JSP there are too much environmental factors which can malform this. The JSP itself also emits some "unintentional" whitespace and other characters. Also, the trimSpaces setting may eat some whitespace/newlines. It's generally considered a poor practice to (ab)use JSP for something else than plain HTML.

Rather use a servlet instead for a robust and consistent CSV output:

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/csv");
    PrintWriter writer = response.getWriter();
    for (ChartDataEntry chartDataEntry : chartData) {
        writer.append(chartDataEntry.getDate()).append(',');
        writer.append(chartDataEntry.getOpen()).append(',');
        writer.append(chartDataEntry.getHigh()).append(',');
        writer.append(chartDataEntry.getLow()).append(',');
        writer.append(chartDataEntry.getClose()).append(',');
        writer.append(chartDataEntry.getVolume()).println();
    }
}
BalusC
Thanks a lot, I think that this would work, but because of the architecture of my project it is not a valid solution for me. I'll have a look to the trimSpaces setting.
Jesus Benito
I finally changed a couple of things and went this way. Thanks a lot!
Jesus Benito
A: 

The code you supplied should generate new lines (probably several of them). Are you sure it isn't a matter of rendering? (i.e. you're looking at it in a browser, and since there is no
tag, the output is rendered on a single line?

Karl Johansson
Thanks for your answer! I have only checked the results in a browser. I'll try to write it in a file. But to be honest I think that this is not the issue, as the application that is reading the csv text is acting as if everything is one line.
Jesus Benito