js 导出到word,excel
1>js导出,原理:复制页面中的table(也可以是其他内容)然后粘贴到excle中
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>导出表格</title>
</head>
<body>
<input type="button" value="导出Word" onclick="JavaScript:exportToWord('tableId')" />
<input type="button" value="导出Excel" onclick="JavaScript:exportToExcel('tableId')" />
<table id="tableId">
<thead>
<tr>
<th>序列</th>
<th>名字</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr>
<td>01</td>
<td>张三</td>
<td>18</td>
<td>女</td>
</tr>
<tr>
<td>02</td>
<td>李四</td>
<td>20</td>
<td>女</td>
</tr>
<tr>
<td>03</td>
<td>王五</td>
<td>22</td>
<td>男</td>
</tr>
<tr>
<td>04</td>
<td>张飞</td>
<td>100</td>
<td>男</td>
</tr>
</tbody>
</table>
</body>
<script type="text/javascript">
function exportToWord(id) {
//Scripting.FileSystemObject (FSO 文本文件读写)被关闭了,
//开启FSO功能即可,在“运行”中执行regsvr32 scrrun.dll即可
try {
var oElement = document.getElementById(id);
var word = new ActiveXObject("Word.Application");
var doc = word.Documents.Add("", 0, 1); //不打开模版直接加入内容
var Range = doc.Range();
var sel = document.body.createTextRange();
sel.moveToElementText(oElement);
sel.select();
sel.execCommand("Copy");
Range.Paste();
word.Application.Visible = true;
}
catch (e) {
alert("无法启动Excel!\n\n" + e.message +
"\n\n如果您确信您的电脑中已经安装了Excel," +
"那么请调整IE的安全级别。\n\n具体操作:\n\n" +
"工具 → Internet选项 → 安全 → 自定义级别 → 对没有标记为安全的ActiveX进行初始化和脚本运行 → 启用");
}
}
function exportToExcel(id) {
//Scripting.FileSystemObject (FSO 文本文件读写)被关闭了,
//开启FSO功能即可,在“运行”中执行regsvr32 scrrun.dll即可
try {
var oElement = document.getElementById(id);
var oRangeRef = document.body.createTextRange();
oRangeRef.moveToElementText(oElement);
oRangeRef.execCommand("Copy");
var oXL = new ActiveXObject("Excel.Application")
var oWB = oXL.Workbooks.Add;
var oSheet = oWB.ActiveSheet;
oSheet.Paste();
oSheet.Cells.NumberFormatLocal = "@";
oXL.Selection.ColumnWidth = 8;
oXL.Visible = true;
oSheet = null;
oWB = null;
appExcel = null;
} catch (e) {
alert("无法启动Excel!\n\n" + e.message +
"\n\n如果您确信您的电脑中已经安装了Excel," +
"那么请调整IE的安全级别。\n\n具体操作:\n\n" +
"工具 → Internet选项 → 安全 → 自定义级别 → 对没有标记为安全的ActiveX进行初始化和脚本运行 → 启用");
}
}
</script>
</html>