JS前端導出EXCEL

  tableToExcel() {
    //要導出的標題
    const columns=[ {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },{
        title: '年齡',
        dataIndex: 'age',
        key: 'age',
      },{
        title: '住址',
        dataIndex: 'address',
        key: 'address',
      }  ],
        //導出的數據
     const   dataSource=[ {
        key: '1',
        name: 'chenchen',
        age: 32,
        address: '西湖區湖底公園1號'
      },{
        key: '2',
        name: 'fangfang',
        age: 32,
        address: '西湖區湖底公園2號' 
      },{
        key: '3',
        name: 'lanlan',
        gugug:"aaaa",
        age: 32,
        address: '西湖區湖底公園3號'
      } ],
      
    // 處理數據
    let newDataSource = []
      for (let i = 0; i < dataSource.length; i++) {
        let tep = {} as any;
        columns.forEach((filter: any) => {
          tep[filter.dataIndex] = dataSource[i][filter.dataIndex]
        })
        newDataSource.push(tep)
      }
    }
    let str = '<tr>';
    for (let i = 0; i < columns.length; i++) {
      str += `<td>${columns[i].title + '\t'}</td>`;
    }
    str += '</tr>';
    str += '<tr>';
    for (let i = 0; i < newDataSource.length; i++) {
      for (let item in newDataSource[i]) {
        let news = newDataSource[i][item] ? newDataSource[i][item] : "";
        //style="mso-number-format:\'@\'" =>excel科學計數
        str += `<td style="mso-number-format:\'@\'">${news + '\t'}</td>`;
      }
      str += '</tr>';
    }
    var worksheet = linkName?linkName:"sheet"//下載之後excel下標顯示名稱(linkName是自己定義的名稱)
    var uri = 'data:application/vnd.ms-excel;base64,';
    var 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">
    <head><meta charset="UTF-8"><!--[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>`;
    var base64 = function(s:any) { return window.btoa(unescape(encodeURIComponent(s))) }
    var link = document.createElement("a");
    link.href = uri+base64(template);
    link.download = linkName?linkName:"download.xls";//當前下載的excel名稱
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link); 
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章