js导出excel(支持图片) 发表于 2020-06-05 | 更新于 2023-01-11 导出excel(支持图片)-test.html123456789101112131415161718192021222324252627<!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.js123456789101112131415161718function test() { exportExcel(document.querySelector('table').outerHTML)}// 导出excelfunction 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)}