Export HTML table to Excel - using jQuery or Java - 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

Related

Using JAVA, how can I parse .cshtml file and add parameters for the existing C# code in that file

I have some .CSHTML files that were incorrectly generated by a tool. I would like to modify the C# code in them to append additional parameters and remove incorrect parameters from method calls.
I've used JSoup to parse the HTML and JSP files. I am able to add or remove attribute in the HTML and JSP files via JSoup DOM iteration.
But in the .CSHTML files contains C# code (I'm new to C#) and couldn't get control over the code. Hence I am not able to append parameters for that C# code using JSoup library. For example,
<td>
#Html.Label(Resource.Get("Label_Name"), new Dictionary<string,object>{{ "Class","label"},{ "name","Name"},{ "id","Name"}})
</td>
<td>
#Html.TextBoxFor(m=> m.TextBox1,new Dictionary<string,object>{{ "Class","txtfield controlWidth"},{ "name","TextBox1"},{ "id","TextBox1"}})
</td>
As above "#Html.xxxx" codes are treated as value for the 'tr' tag in Jsoup DOM iteration. I could only think on adding if..else logic to add or remove parameters as snippet given below. I don't know what is the standard way of parsing such .cshtml file.
if(str.contains("#Html.")) {
ctrlType=str.substring(str.indexOf('.')+1,str.indexOf('('));
if(ctrlType.equalsIgnorecase("Label")) {
// logic to add parameters.
}
}
Using Java, is there way to parse the .cshtml file and add or remove parameters for C# code ? Can you please suggest to solve the problem with open standard API?

JSF, HighCharts and JS

I would like to use in my project highcharts and jsf both. I have a managedbean, which has a list and it is initializing by a facade (it do a query in my database). If I'd like to pass the value of the list to highcharts, how can do this?
if anyone has a good idea, please share.
Best regards and thanks a lot
Haven't worked with highcharts , but I did with other charting library...
I'll give you general Instructions on how to combine js based charting directory it with JSF (I'm sure that there are others way's like using servlets and etc...)
1) build a working "hard coded" js only example in your JSF project
include the relevant *.js files needed by the library
add the "container" div that is required to your page
and finally wrtie the js script that build your chart with hard coded values
2) place your hard coded values into your Bean String property and place a ref' to that property in your .xhtml page something like that <h:inputHidden id="chart_input_data" value="#{myBean.valueOfChart}" /> and access it in your js code like that
//I used jQuery selectors....
var data_for_chart = $('input[id$="chart_input_data"]').val(); //you can use a simpler selector like $("#chart_input_data") too
than use the variable data_for_chart as chart series input (or for whatever parameter of your chart constructor)
3) finally I guess you would like to turn some list of Pojos into a proper json format which is most like wold "fit like a glove" for the HigthCharts constractor , this you can achieve with Gson library something like gson.toJson(yourListOfValues) see Gson user guide
Note
This technique should work for all charting library's , such as flot , flotr2 , gRaphael , jqPlot and more...

java - how to get data of a file from a form?

I've created a form and I need the user to enter some info then upload a picture.
So lets say I have something like this:
<form method="post" enctype="multipart/form-data" action="some servlet/filter">
<input type="file" name="logo">
</form>
I need to use java to change that data to a byte[] then to blob so I can insert to a table.
How do I get the data from this form?
A bit of info on this:
I created the page using javascript, then when submitted it will call a java function to handle the data from the form. It seems that when I submit the form the data for the file is not passed over to the servlet.
So far the few methods I've tried have returned null and I'm outta ideas...
Any examples/help is greatly appreciated!
I think the main question I have is where is the file data stored before the java file start working on it? Is a special global variable holding the data or something like that?
You can use the Apache Commons FileUpload library.
The Commons FileUpload package makes it easy to add robust, high-performance, file upload capability to your servlets and web applications.
FileUpload parses HTTP requests which conform to RFC 1867, "Form-based File Upload in HTML". That is, if an HTTP request is submitted using the POST method, and with a content type of "multipart/form-data", then FileUpload can parse that request, and make the results available in a manner easily used by the caller.
If I understood you right, you need something similar to this example:
http://www.servletworld.com/servlet-tutorials/servlet-file-upload-example.html
I used the following tutorial one year ago:
http://balusc.blogspot.com/2009/12/uploading-files-in-servlet-30.html
It looks like it's a lot, but it's actually easy to understand, and it has a lot of good information.

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

How to download a complete web page (with all its contents) in Java?

Using Java, I need to save a complete webpage(with all its contents like images, css, javascript e.t.c) like how we can do with save as-->complete webpage option with HttpClient lib. How can I do this?
You can try lib curl java
http://curl.haxx.se/libcurl/java/
And you can refer to this discussion also
curl-equivalent-in-java
You have to write an application that fetches the html file, parses it and extracts all the references, and then fetches all the files found by parsing.
It's not so easy because some CSS/JS/Images files paths might be "hidden". Just consider the following example:
<script type="...">
document.write("&bla;script" + " type='...' src='" + blahBlah() + "'&bla;" + "&bla;/script&bla;");
</script>
However, fetching page source, parsing in the search for URLs and downloading founded URLs is pretty everything you'll probably need.

Categories

Resources