1. 程式人生 > 實用技巧 >JS實現純前端將資料匯出Excel兩種方式親測有效

JS實現純前端將資料匯出Excel兩種方式親測有效

由於專案需要,需要在不呼叫後臺介面的情況下,將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:'[email protected]' }, { name:'炮灰乙', phone:'123456', email:'[email protected]' }, { name:'土匪丙', phone:'123456', email:'[email protected]
' }, { name:'流氓丁', phone:'123456', email:'[email protected]' }, ] // 列標題 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:'[email protected]'
            },
            {
                name:'炮灰乙',
                phone:'123456789',
                email:'[email protected]'
            },
            {
                name:'土匪丙',
                phone:'123456789',
                email:'[email protected]'
            },
            {
                name:'流氓丁',
                phone:'123456789',
                email:'[email protected]'
            },
        ];
        // 列標題,逗號隔開,每一個逗號就是隔開一個單元格
        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);
}