How to use JSP/JSTL to create a CSV file - java

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 )?

A better way would be Spring and its JExcelView.

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>

The reason you're getting empty lines is that JSP is rendering empty lines inside your loop. You could eliminate them by packing your loop into one line:
<c:forEach var="rrow" items="${ReportInfo.list}" varStatus="rowCounter">${rrow.subjectCode},${rrow.MCount},${rrow.WCount},${rrow.OCount}</c:forEach>
Or you could add a servlet filter that would strip empty lines from the response.
However, if you want to add special formatting, I believe that goes beyond the comma-separated values format, and you'd need to generate excel native files as suggested by others.
EDIT: Instead of packing your loop into one line, try adding the following directive to your page:
<%#page trimDirectiveWhitespaces="true"%>

In order to create a .xls file, you'll need something heavier-duty than JSTL. Apache POI and JExcelApi are two open-source libraries for generating native Excel format files. POI can generate both .xls and .xlsx; I don't have experience with JExcelApi, but it appears to only support .xls.
As duffymo alluded to, Spring has an AbstractExcelView which you can extend and use with either library. If you're not using Spring, though, you can still use one of the libraries to generate a Workbook object and write its contents to the OutputStream of a ServletResponse. They will also let you format your data in various ways (including bold text) and even create comments and other Excel elements.
For a .xls file you'll want to set the content-type to application/vnd.ms-excel, and for .xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.

JSP is not entirely the right tool for this. Use a servlet class. To save some bytes in Stackoverflow's database, here's just a link to an answer I posted before on the subject: Export to excel using JSP.
That said, I have a few comments on your code and the other answers:
Do not use XLS content type when returning CSV. This will lead to warnings during opening the file. Use the CSV content type: text/csv. Excel perfectly understands this.
Do not render HTML along a wrong content type (the one indicating a XLS(X) file). You're then basically fooling Excel. Since Excel version 2007, it will display warnings about that.

Related

Get all legal Text from HTML File without Library

we have to get out all the Text from an HTML File without the usage of Jsoup or similar. Whats the best/only way to do that? Our Example looks like this:
<ul><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
<h2>An Ordered HTML List</h2>
<ol><li>Coffee</li><li>Tea</li><li>Milk</li></ol>ยดยดยด
need to get all the text out of these html tags without using any libs and if the Tag is not done correctly, print out an error message. Need help guys

Using jade(pug) to create jsp

I would like to write a fast and easy to maintain html/jsp code, so I read about html processors and jade(pug), which seems to be ok for me.
But now I have a problem because I can't/don't know how to:
create file with JSP extension using pug
inject "<%# page contentType="text/html;charset=UTF-8" language="java" %>" from pug to my jsp file
Or maybe there is a different approach for this?
Ok I just solved my problem:
for extension we need to use this
pug index1.pug --extension jsp --pretty
We can just insert this to pug file
From an edit to the question:
Ok I just solved my problem:
for extension we need to use this:
pug index1.pug --extension jsp --pretty
We can just insert this to pug file

JSP library that buffers JavaScript and appends to the end of page

I have a JSP main page that includes multiple page fragments (header, main content, footer etc.). Those fragments contain some Javascript code that is related to them.
Right now the js in those files is at the end of them, wrapped in a jQuery $(document).ready.
Is there a JSP tag / library that I can use to "buffer" / queue all inline Javascript from those fragments and append it at the very end of the main document?
My wishful usage:
main.jsp
<jsp:include page="header.jsp" />
<jsp:include page="main.jsp" />
...
<lib:js-out/>
header.jsp
<h1 id="hi">Hi there</h1>
<lib:js-buffer>
$("#hi").coolAnimation();
</lib:js-buffer>
You could write your own js-buffer tag-lib to save those all to a file which you include at the end. But then, it seems problematic to me. Each time those pages are included its writing the file...which is a waste of resources and could obviously result in write access violations under heavy traffic. Either that or you have to keep track somehow of the update dates on your jsp files and your include files that the tag-lib is creating.

Export HTML table to Excel - using jQuery or Java

I've a HTML table on my JSP page, that I want to be exported to Excel on a button click.
What would be the best way of going about this?
(For ex., how would I do this using may be a jQuery function?)
Any code examples for demo purposes should be great.
I would recommend Apache POI, we've been using it for years, never had any problems.
Alot of examples online to get a good start, and the documentation on the site is also good: http://poi.apache.org/spreadsheet/quick-guide.html
Rather export to CSV format. It's supported by Excel as well. Exporting to a fullworthy XLS(X) format using for example Apache POI HSSF or JExcepAPI is slow and memory hogging.
Exporting to CSV is relatively simple. You can find a complete code example in this answer.
As to exporting to files using JavaScript, this is not possible without interaction of Flash or the server side. In Flash there's as far only the Downloadify library which can export to simple txt files. Further, ExtJs seems to have a CSV export library, but I can't find any feasible demo page.
You can parse the table using a library like http://jsoup.org/
After you get the data, you can store it in Excel-compatible format (CSV), or using Java Excel library for that like POI, or using JDBC to write data into Excel sheet, see this example:
Password Protected Excel File
I also spend lot of time to convert html to excel after lot of R & D i found following easiest way.
create hidden field and in that pass your html data to your servlet or controller for e.g
<form id="formexcel" action="" method="post" name="formexcel">
<input type="hidden" name="exceldata" id="exceldata" value="" />
</form>
on your button of href click call following function and pass your html data using in document.formexcel.exceldata.value and your servlet or controller in document.formstyle.action
function exportDivToExcel() {
document.formexcel.exceldata.value=$('#htmlbody').html();
$("#lblReportForPrint").html("Procurement operation review report");
document.formstyle.method='POST';
document.formstyle.action='${pageContext.servletContext.contextPath}/generateexcel';
document.formstyle.submit();
}
Now in your controller or servlet write following code
StringBuilder exceldata = new StringBuilder();
exceldata.append(request.getParameter("exceldata"));
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=\"exportexcel.xls\"");
outputStream.write(exceldata.toString().getBytes());
Excel can load CSV (comma-separated value) files, which are basically just files with everything that would go into separate Excel cells separated by comma.
I don't know enough about how jQuery can handle pushing information into a file that you would download, but it seems a jQuery library has been written that at least transforms html tables to CSV format, and it is here:
http://www.kunalbabre.com/projects/table2CSV.php
Edit (February 29, 2016):
You can use the table2csv implementation above in conjunction with FileSaver.js (which is a wrapper for the HTML5 W3C saveAs() spec).
The usage will end up looking something like:
var resultFromTable2CSV = $('#table-id').table2CSV({delivery:'value'});
var blob = new Blob([resultFromTable2CSV], {type: "text/csv;charset=utf-8"});
saveAs(blob, 'desiredFileName.csv');
Exporting to Excel file format with JQuery is impossible.
You can try with Java. There are a lot of libraries to do that.
You would have to create something on the server-side (like a servlet) to read the html and create the excel file and serve it back to the user.
You could use this library to help you do the transformation.
I can suggest you to try http://code.google.com/p/gwt-table-to-excel/, at least the server part.
I have been using the jQuery plugin table2excel. It works very well and no serverside coding is needed.
Using it is easy. Simply include jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Now include the table2excel script (Remember to change the src destination to match yours)
<script src="dist/jquery.table2excel.min.js"></script>
Now simply call the script on the table you want exportet.
$("#yourHtmTable").table2excel({
exclude: ".excludeThisClass",
name: "Worksheet Name",
filename: "SomeFile" //do not include extension
});
It's also easy to attach to a button like so:
$("button").click(function(){
$("#table2excel").table2excel({
// exclude CSS class
exclude: ".noExl",
name: "Excel Document Name"
});
});
All examples are taken directly from the authors github page and from jqueryscript.net

Jasper report generating bad HTML

If I view the HTML generated by one of my Jasper reports in IE7 I see the following:
<BR /><BR />
<A name="JR_PAGE_ANCHOR_0_1">
<TABLE style="WIDTH: 1000px" cellSpacing="0" cellPadding="0" bgColor="#ffffff" border="0">
<-- table body omitted -->
</TABLE>
The two BR tags are added via the JRHtmlExporterParameter.HTML_HEADER parameter. After these tags and before the beginning of the report table that there's an unclosed anchor tag that is generated by Jasper reports. The fact that this tag is not correctly closed is messing up the formatting of my report because IE is hyperlinking the entire report TABLE. I'm not using this anchor tag, so if I could prevent Jasper from generating it, that would solve my problem.
Incidentally, this problem only occurs in IE, in Firefox everything works fine because the anchor tag is properly closed.
Thanks in advance,
Don
I took Phil's advice and dove into the Jasper source code. I've fixed the problem and submitted it to the project. Details of the cause and resolution are available here.
That's odd code, the <br /> tags are XHTML-style, while the unclosed a tags are good old HTML, like the upper case tag names. If you serve such page with plain HTML header/content-type, perhaps IE will be happy.
When you write that Firefox closes the tag, I suppose you mean it correctly doesn't extend the hyperlink span over block tags. Note that FF's view source can display closing tags that are not there when you save the page to disk!
Frankly, I don't know if you can get rid of these anchors with some config. If nobody comes with a real solution, maybe you can download Jasper's source code and search JR_PAGE_ANCHOR in it, looking if the code generating it is conditionally driven.
Or, if you can, you can apply post-processing of the generated code.
In excel export A1 cell transfor to JR_PAGE_ANCHOR_0_1.Some of tips are setting IS_ONE_PAGE_PER_SHEET property doing true, IS_DETECT_CELL_TYPE doing true but these are not working for me.
To avoid from this situation , configure your xlsx report configuration is worked for me (set ignore anchor is key point);
private final SimpleXlsxReportConfiguration xlsxReportConfiguration;
JRAbstractExporter exporter;
this.xlsxReportConfiguration = new SimpleXlsxReportConfiguration();
...
xlsxReportConfiguration.setIgnoreAnchors(true);
...
exporter = new JRXlsxExporter();
exporter.setConfiguration(xlsxReportConfiguration);

Categories

Resources