一、数据
1、表头
cols=[
{
"prop": "haxis1Title",
"label": "日期"
},
{
"prop": "haxis2Title",
"label": "数量"
}
]
2、表内容
tableData=[
{
"haxis1Title": "2014",
"haxis2Title": "532.0"
},
{
"haxis1Title": "2015",
"haxis2Title": "609.0"
},
{
"haxis1Title": "2016",
"haxis2Title": "701.0"
},
{
"haxis1Title": "2017",
"haxis2Title": "649.0"
},
{
"haxis1Title": "2018",
"haxis2Title": "656.0"
},
{
"haxis1Title": "2019",
"haxis2Title": "472.0"
},
{
"haxis1Title": "2020",
"haxis2Title": "201.0"
}
]
二、数据拼接为表格样式
html=""
html+="<tr>"
cols.map(item=>{
html+="<th>"+item.label+"</th>"
})
html+="</tr>"
tableData.map(item=>{
html+="<tr>"
cols.map(col=>{
html+="<td>"+item[col.prop]+"</td>"
})
html+="</tr>"
})
console.log(html)
三、拼接excel格式的网页
et template = '';
template += '<html lang="" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel">';
template += '<head><meta charset="UTF-8"><title></title>';
template += '<xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';
template += '<x:Name>';
template += "测试文件";
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>';
四、下载代码
let url = 'data:application/vnd.ms-excel;base64,' + window.btoa(unescape(encodeURIComponent(template)));
//let url = new Blob(['\uFEFF' +template], {type: 'application/vnd.ms-excel;charset=utf-8'})
let a = document.createElement('a');
a.href = url;
a.download = "测试文件";
a.click();
五、中文乱码问题
此处增加:<meta charset="UTF-8">
template += '<head><meta charset="UTF-8"><title></title>';
六、运行结果