利用html里table将json数据导出为excel(.xls)
- 将json数据组装到table标签里,能够在table及其子标签里进行css款式设置。
- 将table增加到html中,在html中退出excel和sheet元素
- 将html编码为excel文件,并进行下载
<script>// 表头数据let thead = [ {text: 'ID', key: 'id'}, {text: '姓名', key: 'name'}, {text: '性别', key: 'sex'}, {text: '身份证号', key: 'idCard'}, {text: '出身日期', key: 'birthday'}, {text: '年龄', key: 'age'}, {text: '联系电话', key: 'tel'},];// 数据组装let tbody = [];let sexArr = ['男', '女'];for (let i = 1; i <= 10; i++) { tbody.push({ id: i, name: 'xx' + i, sex: sexArr[Math.round(Math.random())], idCard: '53010020001111234X', birthday: '2000/11/11', age: 21, tel: 13123456789 });}// 表头数据组装,多级表头let thData = [ [{text: '人员信息表', colspan: thead.length}], [ {text: 'ID', rowspan: 2}, {text: '根本信息', colspan: thead.length - 1}, ], thead.slice(1, thead.length)];exportExcel(thead, tbody, '人员信息表', thData);exportExcel(thead, tbody, sheetName, thData) { /** * 将数据组装到table里 * 减少\t为了不让表格显示迷信计数法或者其余格局 */ let html = ''; if (thData) { // 多级表头 thData.map(list => { html += '</tr>'; list.map(item => { html += `<th colspan="${item.colspan ? item.colspan : 1}" rowspan="${item.rowspan ? item.rowspan : 1}">`; html += item.text + '\t'; html += '</th>'; }); html += '</tr>'; }); } else { // 单级表头 html += '</tr>'; thead.map(item => { html += `<th>`; html += item.text + '\t'; html += '</th>'; }); html += '</tr>'; } tbody.map(item => { html += '<tr>'; thead.map(v => { html += '<td style="text-align: center;">'; html += (item[v.key] ? item[v.key] : '') + '\t'; html += '</td>'; }); html += '</tr>'; }); // 将table增加到html中,在html中退出excel和sheet元素 let template = ''; template += '<html lang="" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel">'; template += '<head><title></title>'; template += '<xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>'; template += '<x:Name>'; template += sheetName; template += '</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>'; template += '</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml>'; template += '</head>'; template += '<body><table>'; template += html; template += '</table></body>'; template += '</html>'; // 将html编码为excel文件,并下载 let url = 'data:application/vnd.ms-excel;base64,' + window.btoa(unescape(encodeURIComponent(template))); let a = document.createElement('a'); a.href = url; a.download = sheetName; a.click();}</script>
成果如下: