前端导出excel可以通过如下方式
tableToExcel(str: string, fileName: string) {
const worksheet = 'Sheet1'
const uri = 'data:application/vnd.ms-excel;base64,'
const 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">
.bg-gray {
background: #aaa;
}
.bg-gray td {
text-align: left;
}
th,td {
text-align: center;
mso-number-format:\@;
vnd.ms-excel.numberformat:\@;
}
</style>
</head><body><table>${str}</table></body></html>`
const a = document.createElement('a')
a.download = fileName + '.xls'
a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
a.click()
}
在我们导出excel时,默认单元格格式为常规,这个时候如果我们单元格中存在0123,或者10.00或者9.0时候,导出后的excel中单元格格式为123,10,9,没能按照原样导出,找了很多文章,网上解决办法是通过给td添加style="mso-number-format:\@;" 这种方式可能对于在微软excel打开没有问题(具体我没有去看),但是我配置完后,发现仍然不生效(可能因为我使用的是wps),通过不断尝试:最终解决方案:
th,td {
text-align: center;
mso-number-format:\@;
vnd.ms-excel.numberformat:\@;
}
添加vnd.ms-excel.numberformat:\@;mso-number-format:\@;添加两种方式。亲测导出数据正常。