1 用WebBrowser控件
<object id="WebBrowser" width=0 height=0
classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></object>
<button onClick="WebBrowser.ExecWB(4,1)">
另存为...
</button>
2 定义一个名为"tableExcel"的表单,再定义一个按钮来onClick。
对JS中的excel.xls可以改为.doc等形式
<script type="text/javascript">
function saveCode(obj) {
var winname = window.open('', '_blank', 'top=10000');
var strHTML = document.all.tableExcel.innerHTML;
winname.document.open('text/html', 'replace');
winname.document.writeln(strHTML);
winname.document.execCommand('saveas','','excel.xls');
winname.close();
}
</script>
3 将页面中指定表格的数据在Excel中打开, 使用ActiveXObject
<SCRIPT LANGUAGE= "javascript" >
function AutomateExcel() {
var oXL = new ActiveXObject( "Excel.Application"); //创建应该对象
var oWB = oXL.Workbooks.Add(); //新建一个Excel工作簿
var oSheet = oWB.ActiveSheet; //指定要写入内容的工作表为活动工作表
var table = document.getElementById("data"); //指定要写入的数据源的id
var hang = table.rows.length; //取数据源行数
var lie = table.rows(0).cells.length; //取数据源列数
//Add table headers going cell by cell.
for (i=0;i <hang;i++) {//在Excel中写行
for (j=0;j <lie;j++) {//在Excel中写列
//定义格式
oSheet.Cells(i+1,j+1).Font.Bold = true;//加粗
oSheet.Cells(i+1,j+1).Font.Size = 10;//字体大小
oSheet.Cells(i+1,j+1).value = table.rows(i).cells(j).innerText;//向单元格写入值
}
}
oXL.Visible = true;
oXL.UserControl = true;
}
</SCRIPT>
4 定义一个名为"tableID"的表单,再用一个按钮onClick
<script type="text/javascript">
function table2xls() {
function String.prototype.Trim() {
return this.replace(/(^s*)|(s*$)/g,"");
}
try {
var e = document.getElementById("tableID");
var s = "";
for (var j=0; j<e.rows.length; j++) {
if (e.rows[0].cells[0].innerText.Trim() == "") {
for (var i=1; i<e.rows[j].cells.length; i++)
s += e.rows[j].cells[i].innerText.Trim() +" ";
} else {
for (var i=0; i<e.rows[j].cells.length; i++)
s += e.rows[j].cells[i].innerText.Trim() +" ";
}
s += " ";
}
var xlsWindow = window.open("","","width=0,height=0");
xlsWindow.document.write(s);
xlsWindow.document.close();
xlsWindow.document.execCommand('Saveas',true,'%homeDrive%\Date.txt')
xlsWindow.close();
}catch(e){}
}
</script>