<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div style="width: 3vw;height: 3vw;border: 1px solid red; display: flex;justify-content: center;align-items: center;" class="statistics_button">导出</div> <script> let data = [{ //模拟数据(假设这就是从后台请求过来的数据) name: "沈阳市", sex: '男', age: '18', education: '高中', employment: '长期派遣', leVel: '一档', item: '真中铁建项目', state: '在职' }, { name: "1", sex: '女', age: '17', education: '高中', employment: '长期派遣', leVel: '一档', item: '中铁建项目', state: '离职' }, { name: "1", sex: '女', age: '17', education: '高中', employment: '长期派遣', leVel: '一档', item: '中铁建项目', state: '离职' }, { name: "3", sex: '男', age: '18', education: '高中', employment: '长期派遣', leVel: '一档', item: '中铁建项目', state: '在职' }, { name: "4", sex: '男', age: '18', education: '高中', employment: '长期派遣', leVel: '一档', item: '中铁建项目', state: '在职' }, { name: "123", sex: '女', age: '17', education: '高中', employment: '长期派遣', leVel: '一档', item: '中铁建项目', state: '离职' }, { name: "131231", sex: '女', age: '17', education: '高中', employment: '长期派遣', leVel: '一档', item: '中铁建项目', state: '离职' }, { name: "7", sex: '男', age: '18', education: '高中', employment: '长期派遣', leVel: '一档', item: '中铁建项目', state: '在职' }, { name: "8", sex: '男', age: '18', education: '高中', employment: '长期派遣', leVel: '一档', item: '中铁建项目', state: '在职' } ] document.getElementsByClassName('statistics_button')[0].onclick = function() { downLoadExcel(data, '统计查询') } 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 = document.createElement("a"); link.href = uri; //对下载的文件命名 link.download = `${fileName || '表格数据'}.xls`; document.body.appendChild(link); link.click(); document.body.removeChild(link); } </script> </body> </html>