Search code examples
javajspcsvjstlexport-to-excel

How to use JSP/JSTL to create a CSV file


I have created a jsp file, with a simple table on it.

I would like to create another jsp file that users can open in Excel or save as an xls.

This is my entire jsp file, this creates a csv file which opens in Excel when a link is clicked:

<%@ page contentType="text/html;charset=windows-1252"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt" %>
<% response.setContentType("application/vnd.ms-excel");
   response.setHeader("Content-Disposition","attachment; filename=" + "online-dashboard.csv" ); %>

<jsp:useBean id="ReportInfo" class="com.reports.ReportLister"  scope="request" />
${ReportInfo.reportType},M,W,Other
<c:forEach var="rrow" items="${ReportInfo.list}"  varStatus="rowCounter">
    ${rrow.subjectCode},${rrow.MCount},${rrow.WCount},${rrow.OCount}
</c:forEach>
Totals,${ReportInfo.totalMSections},${ReportInfo.totalWSections},${ReportInfo.totalOSections}

When I open it in Excel, each row is separated by 2 lines.

Is there an easy way to create an excel file this way?

Is there an easy way to add some formatting ( like bold text for the column headers )?


Solution

  • An easy way is to use the fact that Excel can understand HTML. So simply format your data as an HTML Table and send it as an XLS file. Something like

    <table>
    <c:forEach var="rrow" items="${ReportInfo.list}"  varStatus="rowCounter">
    <tr><td><b>${rrow.subjectCode}</b></td>
        <td>${rrow.MCount}</td>
        <td>${rrow.WCount}</td>
        <td>${rrow.OCount}</td></tr>
    </c:forEach>
    </table>