table导出Excel-表格的内容,格式,颜色不变
程序员文章站
2024-03-19 16:07:28
...
效果图
原代码
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Language" content="zh-cn">
<title>Title</title>
<style>
table td {
font-size: 12px;
width: 200px;
height: 30px;
text-align: center;
background-color: #4f891e;
color: #ffffff;
}
</style>
</head>
<body>
<a download="table导出Excel" id="excelOut" href="#">点击这 table导出Excel</a>
<br/><br/>
<table cellspacing="0" cellpadding="0" border="1" id="table_id">
<thead>
<tr>
<td><b>黄瓜</b></td>
<td><b>茄子</b></td>
<td><b>黄鳝</b></td>
</tr>
</thead>
<tbody>
<tr>
<td>可以吃</td>
<td>可以用</td>
<td>可以养</td>
</tr>
<tr>
<td>可以用</td>
<td>可以吃</td>
<td>可以用</td>
</tr>
<tr>
<td>可以吃和用</td>
<td>可以用和吃</td>
<td>可以养,用,吃</td>
</tr>
<tr>
<td colspan="3">共计3个</td>
</tr>
</tbody>
</table>
<script>
window.onload = function () {
tableToExcel('table_id', '导出结果')
};
//base64转码
var base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)));
};
//替换table数据和worksheet名字
var format = function (s, c) {
return s.replace(/{(\w+)}/g,
function (m, p) {
return c[p];
});
}
function tableToExcel(tableid, sheetName) {
var uri = 'data:application/vnd.ms-excel;base64,';
var 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]-->' +
' <style type="text/css">' +
'table td {' +
'border: 1px solid #000000;' +
'width: 200px;' +
'height: 30px;' +
' text-align: center;' +
'background-color: #4f891e;' +
'color: #ffffff;' +
' }' +
'</style>' +
'</head><body ><table class="excelTable">{table}</table></body></html>';
if (!tableid.nodeType) tableid = document.getElementById(tableid);
var ctx = {worksheet: sheetName || 'Worksheet', table: tableid.innerHTML};
document.getElementById("excelOut").href = uri + base64(format(template, ctx));
}
</script>
</body>
</html>
OK