js导出excel(支持图片)

发布: 2020-06-05 15:32:07标签: 前端开发

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

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

test.js

01function test() {
02 exportExcel(document.querySelector('table').outerHTML)
03}
04
05// 导出excel
06function exportExcel(table, name = `${Date.now()}.xlsx`) {
07 const uri = `data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,`
08 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>`
09 const url = uri + window.btoa(unescape(encodeURIComponent(template)))
10
11 const a = document.createElement('a')
12 a.download = name
13 a.style.display = 'none'
14 a.href = url
15 document.body.appendChild(a)
16 a.click()
17 document.body.removeChild(a)
18}
19
复制代码