js导出Excel表格

时间:2022-12-22 08:14:41

js导出Excel表格

  直接上代码:

  红色部分:如果表格数据中有“1/1”这样的值,会在导出的Excel中转化为日期“1月1日”,所以才加上了红色那两句。如果返回值中没有这样的格式,红色部分可以不写。

 //Excel下载
function base64(content) {
return window.btoa(unescape(encodeURIComponent(content)));
}
function exportOffice(dom, tableID, fName) {
var type = 'excel';
var table = document.getElementById(tableID);
var excelContent = table.innerHTML;
var ddd="<td style=\"mso-number-format:'\\@';\">";
10 var result=((excelContent).toString()).replace(/<td(.*?)>/g,ddd);
console.log(result);
var excelFile = "<html xmlns:v='urn:schemas-microsoft-com:vml' 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 += "<meta http-equiv=Content-Type; content=text/html;charset=UTF-8>";
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><table>";
excelFile += result;
excelFile += "</table></body>";
excelFile += "</html>";
var base64data = "base64," + base64(excelFile);
switch (type) {
case 'excel':
dom.href = 'data:application/vnd.ms-' + type + ';' + base64data;
;//必须是a标签,否则无法下载改名
dom.download = fName;
break;
}
}

  引用:

  1、首先得是a标签。

  2、this:指向a的点击。

  3、'grid-basic':表格的id名。

  4、'统计报表':导出Excel后的表格名

<a onClick="exportOffice(this,'grid-basic','统计报表')">导出Excel</a>

  附上转换红色部分参考文献:https://www.cnblogs.com/zhangym118/p/6378469.html