<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<div id="area1" onclick="jsonToExcel(jsonData,'姓名,电话,邮箱')">123</div>
</head>
<body>
<script>
const jsonData = [
{
name: '路人甲',
phone: '123456789',
email: '000@123456.com'
},
{
name: '炮灰乙',
phone: '123456789',
email: '000@123456.com'
},
{
name: '土匪丙',
phone: '123456789',
email: '000@123456.com'
},
{
name: '流氓丁',
phone: '123456789',
email: '000@123456.com'
},
];
/**
* 导出 json 数据为 Excle 表格
* @param {json} data 要导出的 json 数据
* @param {String} head 表头, 可选 参数示例:'名字,邮箱,电话'
* @param {*} name 导出的文件名, 可选
*/
function jsonToExcel(data, head, name = '导出的文件名') {
let str = head ? head + '\n' : '';
data.forEach(item => {
// 拼接json数据, 增加 \t 为了不让表格显示科学计数法或者其他格式
for (let key in item) {
str = `${str + item[key] + '\t'},`
}
str += '\n'
});
console.log(str,'str');
console.log(encodeURIComponent(str),'str1');
// encodeURIComponent解决中文乱码
const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
// 通过创建a标签实现
const link = document.createElement("a");
link.style.display='none';
link.href = uri;
// window.open(uri,'_blank');
// 对下载的文件命名
link.download = `${name + '.csv'}`;
document.body.appendChild(link)
link.click();
document.body.removeChild(link)
}
</script>
</body>
</html>
通过a标签实现文件下载(json数据转excel格式文件)
最新推荐文章于 2024-05-06 16:08:57 发布