Reputation: 4533
I have a simple table which I would like to export to an Excel file on click of a button.
I wrote a function in JavaScript, but I am not sure what is going wrong.
function CreateExcelSheet()
{
var x=myTable.rows
var xls = new ActiveXObject("Excel.Application")
xls.visible = true
xls.Workbooks.Add
for (i = 0; i < x.length; i++)
{
var y = x[i].cells
for (j = 0; j < y.length; j++)
{
xls.Cells( i+1, j+1).Value = y[j].innerText
}
}
}
This is the button on the JSP page:
</table>
<input type="button" onclick="CreateExcelSheet()" value="Export"></input>
</form>
It used to work earlier but it is not working now. Is there any other way to do this?
Upvotes: 0
Views: 16481
Reputation: 4533
<script language="javascript">
function runApp()
{
var x=myTable.rows;
var Excel = new ActiveXObject("Excel.Application");
Excel.visible = true;
var Book = Excel.Workbooks.Add();
for (i = 0; i < x.length; i++)
{
var y = x[i].cells;
for (j = 0; j < y.length; j++)
{
Book.ActiveSheet.Cells( i+1, j+1).Value = y[j].innerText;
}
}
}
</script>
Upvotes: 0
Reputation: 2896
A really simple alternative is to call a servlet, that servlet returns an xls created from html table tags (this is suitable for really simple tables for complex ones you might want to use POI). From this CodeRanch resource.
in your jsp you have this:
<form method="post" action="DownloadAsExcel"> <input type="submit" name="submit" value="Download as Excel" /> </form>
in your backend :
public class DownloadAsExcel extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res)
{
res.setContentType("application/vnd.ms-excel");
PrintWriter out=res.getWriter();
out.println("<table>");
out.println("<tr bgcolor=lightblue><td>Hello </td><td>James</td></tr>");
out.close();
}
}
Upvotes: 0
Reputation: 8541
You can use Apache POI. This is one example.
http://www.koders.com/java/fid8624B82721FCB1B8C982E6BA5D17D2C7DD87D09C.aspx?s=HSSF+main+excel#L19
It creates "Workbook" , then inside a method called make2 it creates a "Sheet" and add the rows and cells. The values of the cells are passed to the method as Vector.
Another option is that you can use displaytag. The display tag has a feature that allow the user to export the html table to excel file.
Upvotes: 1