CSV jsp generated file, how to insert a break line
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>
It开发者_运维技巧s 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?
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();
}
}
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?
精彩评论