<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p style="font-size: 20px;color: red;">使用table标签方式将json导出xls文件</p>
<button οnclick='tableToExcel()'>导出</button>
<script>
function tableToExcel(){
//要导出的json数据
const jsonData = [
{
name:'路人甲',
phone:'123456789',
email:'[email protected]'
},
{
name:'炮灰乙',
phone:'123456789',
email:'[email protected]'
},
{
name:'土匪丙',
phone:'123456789',
email:'[email protected]'
},
{
name:'流氓丁',
phone:'123456789',
email:'[email protected]'
},
]
//列标题,逗号隔开,每一个逗号就是隔开一个单元格
let str = `姓名,电话,邮箱\n`;
for(let i = 0 ; i < jsonData.length ; i++ ){
for(let item in jsonData[i]){
str+=`${jsonData[i][item] + '\t'},`;
}
str+='\n';
}
//encodeURIComponent解决中文乱码
let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
//通过创建a标签实现
let link = document.createElement("a");
link.href = uri;
//对下载的文件命名
link.download = "json数据表.csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
</script>
</body>
</html>
原文:https://blog.csdn.net/hhzzcc_/article/details/80419396(感谢大佬的分享)