Export HTML Table to Excel with JS

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script Language="javascript">
        function TableToExcel() {
            var strCopy = document.getElementById("detailsTable").innerHTML;
            window.clipboardData.setData("Text", strCopy);
            var objExcel = new ActiveXObject("Excel.Application");
            objExcel.visible = true;

            var objWorkbook = objExcel.Workbooks.Add;
            var objWorksheet = objWorkbook.Worksheets(1);

        function exportToExcel() {
            var oExcel = new ActiveXObject("Excel.Application");
            var oBook = oExcel.Workbooks.Add;
            var oSheet = oBook.Worksheets(1);
            for (var y = 0; y < detailsTable.rows.length; y++)
            // detailsTable is the table where the content to be exported is
                for (var x = 0; x < detailsTable.rows(y).cells.length; x++) {
                    oSheet.Cells(y + 1, x + 1) = detailsTable.rows(y).cells(x).innerText;
            oExcel.Visible = true;
            oExcel.UserControl = true;
    <table id="detailsTable" border="1">
    <input id="clickExcel" type="button" value="button" onclick="javascript:TableToExcel()"/>
    <a href="javascript:exportToExcel();">Export to Excel</a><br/>

Print | posted @ Monday, July 16, 2012 3:56 PM

Comments on this entry:

Gravatar # re: Export HTML Table to Excel with JS
by Harpreet at 10/24/2012 7:37 AM

This code is not helpful:
1: if Ms Excel is not installed
2: The Browser security settings needs modification which risks the security
3: It always through's automation server object not found error
Gravatar # re: Export HTML Table to Excel with JS
by Ricardo Silva at 11/26/2012 10:07 AM

It works with openoffice or libreoffice?

best regards
Gravatar # re: Export HTML Table to Excel with JS
by Sagar Mali at 2/13/2013 10:03 AM

Works with only IE
Post A Comment