
正文
JS生成EXCEL(Chrome浏览器)
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
直接使用js+Html生成excel文件,当前版本:chrome浏览器
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
table{border-collapse: collapse; }
th, td{border: 1px solid #4d4d4d;padding: 5px; }
</style>
<script type="text/javascript" language="javascript">
var idTmr;
function getExplorer() {
var explorer = window.navigator.userAgent ;
if(explorer.indexOf("Chrome") >= 0){
return 'Chrome';
}else{
alert("非chrome浏览器");
return false;
}
}
function method1(tableid) {//整个表格拷贝到EXCEL中
tableToExcel('tableId')
}
var tableToExcel = (function(tableId) {
//设置类型
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
//base64加密处理
base64 = function(s) {
return window.btoa(unescape(encodeURIComponent(s)))
},
//格式化处理
format = function(s, c) {
return s.replace(/{(\w+)}/g,
function(m, p) {
return c[p];
}
)
};
//自动执行
return function(tableId, name) {
var aLink=document.getElementById("dlink");
var table = document.getElementById(tableId);
// 获取表单的名字和表单查询的内容
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
// format()函数:通过格式操作使任意类型的数据转换成一个字符串
// base64():进行编码
aLink.href = uri + base64(format(template, ctx))
aLink.download="test.xls";
aLink.click();
}
})()
</script> </head>
<body>
<table id="tableId">
<tr>
<th></th>
<th>一</th>
<th>二</th>
<th>三</th>
<th>四</th>
</tr>
<tr>
<td>万籁寂无声</td>
<td>衾铁棱棱近五更</td>
<td>香断灯昏吟未稳</td>
<td>凄清</td>
<td>只有霜华伴月明</td>
</tr>
<tr>
<td>应是夜寒凝</td>
<td>恼得梅花睡不成</td>
<td>我念梅花花念我</td>
<td>关情</td>
<td>起看清冰满玉瓶</td>
</tr>
</table>
<br/>
<a id="dlink" style="display: none;"></a>
<input type="button" value="导出EXCEL" onclick="method1('tableId')" />
</body>
</html>








