由於項目需要,需要在不調用后台接口的情況下,將json數據導出到excel表格,參考了好多資料以及很多大佬寫的博客終於實現,兼容chrome沒問題,其他還沒有測試過,這邊介紹兩種實現方式,並附上代碼和gif動圖,博主不才還望輕噴,代碼可直接copy運行
方法一
將table標簽,包括tr、td等對json數據進行拼接,將table輸出到表格上實現,這種方法的弊端在於輸出的是偽excel,雖說生成xls為后綴的文件,但文件形式上還是html,代碼如下:
<html> <meta charset="UTF-8"> <head> <p style="font-size: 20px;color: red;">使用table標簽方式將json導出xls文件</p> <button onclick='tableToExcel()'>導出</button> </head> <body> <script> const tableToExcel = () => { // 要導出的json數據 const jsonData = [ { name:'路人甲', phone:'123456', email:'123@123456.com' }, { name:'炮灰乙', phone:'123456', email:'123@123456.com' }, { name:'土匪丙', phone:'123456', email:'123@123456.com' }, { name:'流氓丁', phone:'123456', email:'123@123456.com' }, ] // 列標題 let str = '<tr><td>姓名</td><td>電話</td><td>郵箱</td></tr>'; // 循環遍歷,每行加入tr標簽,每個單元格加td標簽 for(let i = 0 ; i < jsonData.length ; i++ ){ str+='<tr>'; for(const key in jsonData[i]){ // 增加\t為了不讓表格顯示科學計數法或者其他格式 str+=`<td>${ jsonData[i][key] + '\t'}</td>`; } str+='</tr>'; } // Worksheet名 const worksheet = 'Sheet1' const uri = 'data:application/vnd.ms-excel;base64,'; // 下載的表格模板數據 const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"> <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"> <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"> <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet> <x:Name>${worksheet}</x:Name> <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet> </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--> </head><body><table>${str}</table></body></html>`; // 下載模板 window.location.href = uri + base64(template); }; // 輸出base64編碼 const base64 = s => window.btoa(unescape(encodeURIComponent(s))); </script> </body> </html>
方法二
通過將json遍歷進行字符串拼接,將字符串輸出到csv文件,代碼如下:
<html> <head> <p style="font-size: 20px;color: red;">使用a標簽方式將json導出csv文件</p> <button onclick='tableToExcel()'>導出</button> </head> <body> <script> const tableToExcel = () => { // 要導出的json數據 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' }, ]; // 列標題,逗號隔開,每一個逗號就是隔開一個單元格 let str = `姓名,電話,郵箱\n`; // 增加\t為了不讓表格顯示科學計數法或者其他格式 for(let i = 0 ; i < jsonData.length ; i++ ){ for(const key in jsonData[i]){ str+=`${jsonData[i][key] + '\t'},`; } str+='\n'; } // encodeURIComponent解決中文亂碼 const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str); // 通過創建a標簽實現 const link = document.createElement("a"); link.href = uri; // 對下載的文件命名 link.download = "json數據表.csv"; link.click(); } </script> </body> </html>
封裝成方法
function exportExcel(JSONData, FileName, title, filter) { if (!JSONData) return; //轉化json為object var arrData = typeof JSONData != "object" ? JSON.parse(JSONData) : JSONData; var excel = "<table>"; //設置表頭 var row = "<tr>"; if (title) { //使用標題項 for (var i in title) { if (filter.indexOf(i) == -1) { row += "<th align='center'>" + title[i] + "</th>"; } } } else {//不使用標題項 for (var i in arrData[0]) { if (filter.indexOf(i) == -1) { row += "<th align='center'>" + i + "</th>"; } } } excel += row + "</tr>"; //設置數據 for (var i = 0; i < arrData.length; i++) { var row = "<tr>"; for (var index in arrData[i]) { if (filter.indexOf(index) == -1) { var value = arrData[i][index] == null ? "" : arrData[i][index]; row += "<td align='center'>" + value + "</td>"; } } excel += row + "</tr>"; } excel += "</table>"; var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>"; excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">'; excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel'; excelFile += '; charset=UTF-8">'; excelFile += "<head>"; excelFile += "<!--[if gte mso 9]>"; excelFile += "<xml>"; excelFile += "<x:ExcelWorkbook>"; excelFile += "<x:ExcelWorksheets>"; excelFile += "<x:ExcelWorksheet>"; excelFile += "<x:Name>"; excelFile += "{worksheet}"; excelFile += "</x:Name>"; excelFile += "<x:WorksheetOptions>"; excelFile += "<x:DisplayGridlines/>"; excelFile += "</x:WorksheetOptions>"; excelFile += "</x:ExcelWorksheet>"; excelFile += "</x:ExcelWorksheets>"; excelFile += "</x:ExcelWorkbook>"; excelFile += "</xml>"; excelFile += "<![endif]-->"; excelFile += "</head>"; excelFile += "<body>"; excelFile += excel; excelFile += "</body>"; excelFile += "</html>"; var uri = "data:application/vnd.ms-excel;charset=utf-8," + encodeURIComponent(excelFile); var link = document.createElement("a"); link.href = uri; link.style = "visibility:hidden"; link.download = FileName + ".xls"; document.body.appendChild(link); link.click(); document.body.removeChild(link); }