这是我的一个朋友发我的 给大家分享一下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery.min.js"></script>
<title></title>
</head>
<body>
<button id="" type="button" class="importBtn">
<i></i> 导出</button>
<script type="text/javascript">
let data = [{
"name": "张三一",
"gender": "女",
"age": "22",
"record": "初中及以下",
"employment": "长期派遣",
"level": "一档2级",
"item": "河南铁路",
"status": "在职"
},
{
"name": "张三",
"gender": "男",
"age": "18",
"record": "高中",
"employment": "学员",
"level": "一档2级",
"item": "河南铁路",
"status": "在职"
},
{
"name": "王五",
"gender": "男",
"age": "22",
"record": "大学",
"employment": "长期派遣",
"level": "一档1级",
"item": "电路",
"status": "在职"
}
]
$(".importBtn").on('click', function() {
var tableData = [];
console.log(data);
tableData = data;
downLoadExcel(tableData, '工资社保管理')
})
function downLoadExcel(data, fileName) {
//定义表头
let str = '姓名,性别,年龄,学历,用工形式,档级,所在项目,在职状态,\n';
//增加\t为了不让表格显示科学计数法或者其他格式
for (let i = 0; i < data.length; i++) {
for (let item in data[i]) {
str += `${data[i][item] + '\t'},`;
}
str += '\n';
}
//encodeURIComponent解决中文乱码
let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
//通过创建a标签实现
let link_data = document.createElement("a");
link_data.href = uri;
//对下载的文件命名
link_data.download = `${fileName || '表格数据'}.xls`;
document.body.appendChild(link_data);
link_data.click();
document.body.removeChild(link_data);
}
</script>
</body>
</html>