纯js实现数据excel导出功能
<!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>导出excel</title> </head> <body> <button id="export">导出excel</button> </body> <script> /** * 导出表格数据到 Excel 文件 * @param {Array} tableData - 表格数据 * @param {Array} fieldLabels - 表头组成的数组 * @param {Array} fieldKeys - 列属性名组成的数组 * @param {String} fileName - 导出的文件名 */ function exportExcel(tableData, fieldLabels, fieldKeys, fileName) { let dataStr = fieldLabels.toString() + '\r\n'; tableData.forEach((item, index) => { item.Index = index + 1; fieldKeys.forEach(key => { // 加引号是为了使换行符在单元格内正常显示 dataStr += `"${item[key] ? item[key] : ''}"\t,`; }); dataStr += '\r\n'; }); // encodeURIComponent 解决中文乱码 const url = "data:text/xls;charset=utf-8,\ufeff" + encodeURIComponent(dataStr); const link = document.createElement("a"); link.href = url; link.download = fileName + ".xls"; link.style.display = 'none'; document.body.appendChild(link); link.click(); document.body.removeChild(link); //释放标签 } const tableData = [ { date: '2016-05-02', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄' }, { date: '2016-05-04', name: '张小星', address: '上海市普陀区金沙江路 1517 弄' }, { date: '2016-05-01', name: '刘小备', address: '上海市普陀区金沙江路 1519 弄' }, { date: '2016-05-03', name: '赵小云', address: '上海市普陀区金沙江路 1516 弄' } ], fieldKeys = ['date', 'name', 'address'], fieldLabels = ['日期', '姓名', '地址'], fileName = '测试文件'; document.getElementById('export').addEventListener('click', function (e) { exportExcel(tableData, fieldLabels, fieldKeys, fileName); }) </script> </html>