Export html table to excel directly by using javascript
I trying to export the html table to excel by using javascript and I managed to get the sample ( source code as below).The sample below will automatically export all the records in html table into excel directly.
function write_to_excel()
{
str="";
var mytable = document.getElementsByTagName("table")[0];
var rowCount = mytable.rows.length;
var colCount = mytable.getElementsByTagName("tr")[0].getElementsByTagName("td").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = false;
for(var i=0; i<rowCount; i++)
{
for(var j=0; j<colCount; j++)
{
str= mytable.getElementsByTagName("tr")[i].getElementsByTagName("td")[j].innerHTML;
ExcelSheet.ActiveSheet.Cells(i+1,j+1).Value = str;
}
}
ExcelSheet.SaveAs("C:\\TEST.XLS");
// Close Excel with the Quit method on the Application object.
ExcelSheet.Application.Quit();
}
function write_to_csv()
{
str="";
var mytable = document.getElementsByTagName("table")[0];
var rowCount = mytable.rows.length;
var colCount = mytable.getElementsByTagName("tr")[0].getElementsByTagName("td").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
var mytable = document.getElementsByTagName("table")[0];
var rowCount = mytable.rows.length;
var colCount = mytable.getElementsByTagName("tr")[0].getElementsByTagName("td").length;
for(var i=0; i<rowCount; i++)
{
for(var j=0; j<colCount; j++)
{
str= str + mytable.getElementsByTagName("tr")[i].getElementsByTagName("td")[j].innerHTML + ",";
}
ExcelSheet.ActiveSheet.Cells(i+1,1).Value = str;
str="";
}
}
</script>
</head>
<body>
<input type="submit" value="Export to EXCEL" onclick="write_to_excel();"/>
<input type="submit" value="Export to CSV" onclick="write_to_csv();"/>
<br />
<div id="Book1_10219" align=center x:publishsource="Excel">
<table>
<tr><td>123</td><td>test 2</td></tr>
<tr><td>test5</td><td>test 2</td></tr>
</table>
</div>
<body>
</html>
Comments
Post a Comment