html table转excel单元格带背景颜色
在浏览器端将html的table转成Excel,可以参考下面的库
https://github.com/JackGit/table2excel.js
下面是使用这个库写的一个例子。
如果项目中有其他css样式文件设置了table的font-family,可能会导致导出的Excel报错,并使table中设置的单元格背景色失效。
碰到这种情况可以强制在table中设置一种不报错的font-family样式,覆盖掉其他font-family样式。
例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 直接使用exceljs.min.js就不用再导入依赖的ExcelJS -->
<script src="./exceljs.min.js"></script>
<script>
function downloadTable2Excel() {
new Table2Excel('#table1').export();
}
</script>
</head>
<body>
<button onclick="downloadTable2Excel()">table2excel</button>
<!-- 有些字体可能会导致转成Excel后报错,导致单元格的背景颜色没有带出 -->
<table id="table1" style="font-family: Arial, monospace, sans-serif !important;">
<thead>
<tr>
<th style="background-color: #00aced">ID</th>
<th style="background-color: #00aced">Name</th>
<th style="background-color: #00aced">Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Tom</td>
<td>aaaaaaa</td>
</tr>
<tr>
<td>2</td>
<td>John</td>
<td>wwwww</td>
</tr>
</tbody>
</table>
</body>
</html>
导出效果如下: