js导出excel(支持图片)

导出excel(支持图片)-test.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>导出excel(支持图片)</title>
</head>
<body>
<table style="border-collapse: collapse;" border="1" cellspacing="0" cellpadding="0">
<tr>
<td style="width: 50px; height: 50px;">
<img style="width: 50px; height: 50px;" src="http://pic.kuan1.top/38d54e7711a19ac1ca08f134934bdbf3.png" />
</td>
<td style="width: 50px; height: 50px;">
<span>图片</span>
</td>
<td style="width: 50px; height: 50px;">
<img style="width: 50px; height: 50px;" src="http://pic.kuan1.top/38d54e7711a19ac1ca08f134934bdbf3.png" />
</td>
</tr>
</table>
<p>
<button onclick="test()">导出excel</button>
</p>
<script src="./test.js"></script>
</body>
</html>

test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function test() {
exportExcel(document.querySelector('table').outerHTML)
}

// 导出excel
function exportExcel(table, name = `${Date.now()}.xlsx`) {
const uri = `data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;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><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>${name}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>${table}</body></html>`
const url = uri + window.btoa(unescape(encodeURIComponent(template)))

const a = document.createElement('a')
a.download = name
a.style.display = 'none'
a.href = url
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}