现在各大浏览器基本都支持data协议,所以我们可以使用该协议去将网页中的table转化为excel下载下来
- 对html 进行base64编码处理
- 编码后的html内容增加前缀 data:application/vnd.ms-excel; ,即可使浏览器将其中的数据当做excel来处理,浏览器将提示下载或打开excel文件
代码小例:
<html>
<head>
<meta http-equiv="content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript">
function base64 (content) {
return window.btoa(unescape(encodeURIComponent(content)));
}
function exportOffice(tableID){
var type = 'doc';
var table = document.getElementById(tableID);
var excelContent = table.innerHTML;
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 += excelContent;
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;
}
}
</script>
</head>
<body>
<table id="targetTable">
<tr align="center">
<th>名次</th>
<th>姓名</th>
<th>成绩</th>
</tr>
<tr align="center">
<td>1</td>
<td>小明</td>
<td>100</td>
</tr>
<tr align="center">
<td>2</td>
<td>小红</td>
<td>95.5</td>
</tr>
</table>
</br>
<input id="Button1" type="button" value="导出"
onclick="exportOffice('targetTable')" />
</body>
</html>