var idTmr = "";
function copy(tabid)
{
var oControlRange = document.body.createControlRange();
oControlRange.add(tabid,0);
oControlRange.select();
document.execCommand("Copy");
}
function toExcel(tabid){
copy(tabid);
try
{
var xls = new ActiveXObject("Excel.Application");
}
catch(e)
{
alert( "Excel没有安装或浏览器设置不正确.请启用所有Active控件和插件");
return false;
}
xls.visible = true;
var xlBook = xls.Workbooks.Add;
var xlsheet = xlBook.Worksheets(1);
xlBook.Worksheets(1).Activate;
for(var i=0;i<tabid.rows(0).cells.length;i++){
xlsheet.Columns(i+1).ColumnWidth=15;
}
xlsheet.Paste;
xls=null;
idTmr = window.setInterval("Cleanup();",1);
}
function Cleanup() {
window.clearInterval(idTmr);
CollectGarbage();
}
===========================使用示例==============================
<table id="export_table" width="99%" cellspacing="0" cellpadding="0" border="1" style="display:none;">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</table>
<input type="button" value="导出Excel" onclick="toExcel(export_table)"/>