0

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?

1
  • Are you aware that ActiveX works in MSIE only, not in other browsers? Commented Sep 27, 2011 at 13:34

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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(); } } 

1 Comment

You should not fool Excel with a HTML table with the wrong content type. This will finally end up in trouble in all colors. Rather return a real XLS file or just a CSV file.
0
<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> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.