前端js原生导出excel,显示边框和风格线
2021-07-22 本文已影响0人
Mcq
let html = document
.querySelector('table')
.outerHTML.replace(/<(\w+) (.+?)>/g, (m, p1) => `<${p1}>`)
.replace('<table>', '<table border>')
// vnd.ms-excel.numberformat:@; 格式化文本
// xmlns 和 head 中 用于显示网格线
html = `<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:WorksheetOptions>
<x:Print><x:ValidPrinterInfo /></x:Print>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
</head>
<style>
table{vnd.ms-excel.numberformat:@;}
</style>
${html}
</html>`
const excelBlob = new Blob([html], { type: 'application/vnd.ms-excel' })
const a = document.createElement('a')
a.href = URL.createObjectURL(excelBlob)
a.download = 'excel.xls'
a.click()
URL.revokeObjectURL(a.href) // 释放资源