function exportExcel(FileName = '数据统计', JSONData = [], columns = []) {
let excel = '<table>';
//设置表头
let row = '<tr>';
for (let i = 0, l = columns.length; i < l; i+=1) {
row += `<td>${columns[i].title}</td>`;
}
//换行
excel += `${row}</tr>`;
//设置数据
for (let i = 0; i < JSONData.length; i+=1) {
let row = '<tr>';
for (let j = 0; j < columns.length; j+=1) {
let value = JSONData[i][columns[j].key];
row += `<td>${value}</td>`;
}
excel += `${row}</tr>`;
}
excel += '</table>';
const excelFile = `
<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'>
<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
<head>
<!--[if gte mso 9]>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>
{worksheet}
</x:Name>
<x:WorksheetOptions>
<x:DisplayGridlines/>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
<![endif]-->
</head>
<body>
${excel}
</body>
</html>
`;
const link = document.createElement('a');
link.href = `data:application/vnd.ms-excel;charset=utf-8,${encodeURIComponent(excelFile)}`;
link.style = 'visibility:hidden';
link.download = `${FileName}.xls`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
let excel = '<table>';
//设置表头
let row = '<tr>';
for (let i = 0, l = columns.length; i < l; i+=1) {
row += `<td>${columns[i].title}</td>`;
}
//换行
excel += `${row}</tr>`;
//设置数据
for (let i = 0; i < JSONData.length; i+=1) {
let row = '<tr>';
for (let j = 0; j < columns.length; j+=1) {
let value = JSONData[i][columns[j].key];
row += `<td>${value}</td>`;
}
excel += `${row}</tr>`;
}
excel += '</table>';
const excelFile = `
<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'>
<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
<head>
<!--[if gte mso 9]>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>
{worksheet}
</x:Name>
<x:WorksheetOptions>
<x:DisplayGridlines/>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
<![endif]-->
</head>
<body>
${excel}
</body>
</html>
`;
const link = document.createElement('a');
link.href = `data:application/vnd.ms-excel;charset=utf-8,${encodeURIComponent(excelFile)}`;
link.style = 'visibility:hidden';
link.download = `${FileName}.xls`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
注: const columns = [
{
key: 'title',
title: '报告名称',
}, {
key: 'type',
title: '类型',
}]
const data = [{title: 'xxxx', type='sda'}]