<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p style="font-size: 20px;">json格式导出excel文件</p>
<button onclick='tableToExcel()'>导出</button>
<script>
function tableToExcel() {
//要导出的json数据
const jsonData = [{
name: '张三',
phone: '123456',
email: '123@123456.com'
}, {
name: '李四',
phone: '123456',
email: '123@123456.com'
}, {
name: '王五',
phone: '123456',
email: '123@123456.com'
}, {
name: '老六',
phone: '123456',
email: '123@123456.com'
}, ]
//列标题
let head = `<tr><th>表头1</th><th>表头2</th><th>表头3</th></tr>`;
let tbody = ""; //内容
for (let item in jsonData) {
tbody +=
`<tr>
<td>${jsonData[item].name + '\t'}</td>
<td>${jsonData[item].phone + '\t'}</td>
<td>${jsonData[item].email + '\t'}</td>
</tr>`
}
let str = head + tbody; //头部跟身体内容连接
//Worksheet名
let worksheet = 'Sheet1'
let uri = 'data:application/vnd.ms-excel;base64,';
//下载的表格模板数据
let 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><!--[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><table border="1">${str}</table></body></html>`;
//下载模板
console.log(str)
window.location.href = uri + base64(template)
}
//输出base64编码
function base64(s) {
return window.btoa(unescape(encodeURIComponent(s)))
}
</script>
</body>
</html>