saveTableToXls
// ==UserScript==
// @name saveTableToXls
// @author major
// @version 1.0.4
// @require https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js
// ==/UserScript==
// 保存方式1
function saveTableToXls(tableHTML){
function base64 (content) {
return window.btoa(unescape(encodeURIComponent(content)));
};
var type = 'excel';
var excelContent = tableHTML;
var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:"+type+"' xmlns='http://www.w3.org/TR/REC-html40'>";
excelFile += "<head>";
excelFile += "<!--[if gte mso 9]>";
excelFile += "<xml>";
excelFile += "<x:ExcelWorkbook>";
excelFile += "<x:ExcelWorksheets>";
excelFile += "<x:ExcelWorksheet>";
excelFile += "<x:Name>";
excelFile += "{worksheet}";
excelFile += "</x:Name>";
excelFile += "<x:WorksheetOptions>";
excelFile += "<x:DisplayGridlines/>";
excelFile += "</x:WorksheetOptions>";
excelFile += "</x:ExcelWorksheet>";
excelFile += "</x:ExcelWorksheets>";
excelFile += "</x:ExcelWorkbook>";
excelFile += "</xml>";
excelFile += "<![endif]-->";
excelFile += "</head>";
excelFile += "<body>";
excelFile += "<table>";
excelFile += excelContent;
excelFile += "</table>";
excelFile += "</body>";
excelFile += "</html>";
var base64data = "base64," + base64(excelFile);
switch(type){
case 'excel':
window.open('data:application/vnd.ms-'+type+';'+base64data);
break;
case 'powerpoint':
window.open('data:application/vnd.ms-'+type+';'+base64data);
break;
}
};
// 保存方式2 支持 xls 和 xlsx格式
function saveTableToXls_2(tableHTML,file_name="导出的文件.xlsx"){
//window.location.href='<%=basePath%>pmb/excelShowInfo.do';
//获取表格
// var exportFileContent = document.getElementById("table_report").outerHTML;
// var exportFileContent = document.querySelector(".auxo-table-content table").outerHTML;
var exportFileContent = tableHTML;
//设置格式为Excel,表格内容通过btoa转化为base64,此方法只在文件较小时使用(小于1M)
//exportFileContent=window.btoa(unescape(encodeURIComponent(exportFileContent)));
//var link = "data:"+MIMEType+";base64," + exportFileContent;
//使用Blob
var blob = new Blob([exportFileContent], {type: "text/plain;charset=utf-8"}); //解决中文乱码问题
blob = new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
//设置链接
var link = window.URL.createObjectURL(blob);
var a = document.createElement("a"); //创建a标签
a.download = file_name; //设置被下载的超链接目标(文件名)
a.href = link; //设置a标签的链接
document.body.appendChild(a); //a标签添加到页面
a.click(); //设置a标签触发单击事件
document.body.removeChild(a); //移除a标签
};