使用js将页面上的table导出成excel表格

转自于:https://blog.csdn.net/qq_41594146/article/details/82288841

function base64(content) {
  return window.btoa(unescape(encodeURIComponent(content)));
}
function tableToExcel(tableID, fileName) {
  var excelContent = $("#" + tableID).html();
  // alert(excelContent);
  var excelFile = "<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'>";
  excelFile += "<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>";
  excelFile += "<body><table width='10%' border='1'>";
  excelFile += excelContent;
  excelFile += "</table></body>";
  excelFile += "</html>";
  var link = "data:application/vnd.ms-excel;base64," + base64(excelFile);
  var a = document.createElement("a");
  a.download = fileName + ".xlsx";
  a.href = link;
  a.click();
}

在js区域中加入上面这段代码.

设置一个按钮调用上面的tableToExcel方法,第一个参数是你需要转成excel表格的table的id ,第二个参数是excel文件的名字 

就OK了

 

例如:

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title></title>
</head>
<script src="js/jquery-3.2.1.min.js" type="text/javascript" charset="utf-8"></script>
<body>
<table id="tabDiv1">
<tr>
<td>ID</td>
<td>姓名</td>
<td>年龄</td>
</tr>
<tr>
<td>0001</td>
<td>张三</td>
<td>24</td>
</tr>
</table>
<button onclick="tableToExcel();">export to excel...</button>
<script type="text/javascript">
function base64(content) {
return window.btoa(unescape(encodeURIComponent(content)));
}

function tableToExcel(tableID, fileName) {
var excelContent = $("#tabDiv1").html();
// alert(excelContent);
var excelFile = "<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'>";
excelFile += "<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>";
excelFile += "<body><table width='10%' border='1'>";
excelFile += excelContent;
excelFile += "</table></body>";
excelFile += "</html>";
var link = "data:application/vnd.ms-excel;base64," + base64(excelFile);
var a = document.createElement("a");
a.download = "fileName" + ".xlsx";
a.href = link;
a.click();
}

</script>
</body>

</html>

posted @ 2021-02-21 10:26  Ao_min  阅读(769)  评论(0编辑  收藏  举报