效果圖:
調用代碼:
// 列 let column = [ { text: '姓名', key: 'name' }, { text: '身份證', key: 'personId' }, { text: '手機號', key: 'phone' }, ]; // 表頭 let headData = [ [{ text: '幼兒園一年級', colspan: 3 }], [ { text: '姓名', key: 'name' }, { text: '身份證', key: 'personId' }, { text: '手機號', key: 'phone' }, ] ]; // 表體 let bodyData = [ { name: '張三', personId: '12345601', phone: '15211112222', }, { name: '李四', personId: '12345602', phone: '15211112222', }, { name: '王五', personId: '12345603', phone: '15211112222', }, ] jsonToExcel(column, headData, bodyData, '幼兒園一年級')
核心方法:
/** * 導出 json 數據爲 Excle 表格 * @param {json} column 列 * @param {json} headData 表頭數據 * @param {json} bodyData 表體數據 * @param {string} sheetName 導出的文件名, 可選 * 增加 \t 爲了不讓表格顯示科學計數法或者其他格式 */ function jsonToExcel(column, headData, bodyData, sheetName = 'Excle表格') { // 組裝表頭 let theadHtml = ''; headData.map(list => { let th = '' list.map(item => { th += ` <th colspan="${item.colspan || 1}" rowspan="${item.rowspan || 1}"> ${item.text + '\t'} </th> `; }); theadHtml += `<tr>${th}</tr>` }); // 組裝表體 let tbodyHtml = '' bodyData.map(item => { let td = '' column.map(n => { const val = item[n.key] || '' td += `<td style="text-align: center;">${val + '\t'}</td>` }); tbodyHtml += `<tr>${td}</tr>` }); // 將table添加到html中,在html中加入excel和sheet元素 let template = ` <html lang="" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"> <head> <title></title> <xml> <x:ExcelWorkbook> <x:ExcelWorksheets> <x:ExcelWorksheet> <x:Name>${sheetName}</x:Name> <x:WorksheetOptions> <x:DisplayGridlines/> </x:WorksheetOptions> </x:ExcelWorksheet> </x:ExcelWorksheets> </x:ExcelWorkbook> </xml> </head> <body> <table> <thead>${theadHtml}</thead> <tbody>${tbodyHtml}</tbody> </table> </body> </html> `; // encodeURIComponent 解決中文亂碼 const uri = 'data:text/xlsx;charset=utf-8,\ufeff' + encodeURIComponent(template); // 通過創建a標籤實現 const link = document.createElement("a"); link.href = uri; link.download = `${sheetName + '.xlsx'}`; // 設置文件名 link.click(); }