前端实现table导出excel

2,648 阅读1分钟

工作中遇到要将页面table导出为excel的请求,解决方法有两种,一是将tabledom遍历导出excel,而是组织好table数据导出,现记录下第二种的方案:

1. 组织要导出的json数据

const jsonData = [
    { name: '001', id: '621699190001011231' },
    { name: '002', id: '52069919000101547X' },
    { name: '003', id: '423699190103015469' },
    { name: '004', id: '341655190105011749' }
]

2.导出前将json数据转成table格式

// 列标题
const str = '<tr><td>name</td><td>id</td></tr>'
//具体数值遍历
jsonData.forEach((e,i) => {
    str += '<tr>'
    for (let item in jsonData[i]) {
      var cellvalue = jsonData[i][item]
      str += `<td style="mso-number-format:'\@';">${cellvalue}</td>`
      // str+=`<td>${cellvalue}</td>`;
    }
    str += '</tr>'
 })
 const worksheet = '导出结果'
 const uri = 'data:application/vnd.ms-excel;base64,'

注:导出的表格如果有数字过长灰显示科学技术法或其他格式,可以用以下办法解决

  1. tr里面加style="mso-number-format:'\@';"
  2. 改为string类型
const reg = /^[0-9]+.?[0-9]*$/;
if ((cellvalue.length>15) && (reg.test(cellvalue))){
    cellvalue = '="' + cellvalue + '"';
 }

3.下载的表格模板数据

  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">
        <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>`

4.下载模板

function base64(s) {
    return window.btoa(unescape(encodeURIComponent(s)))
  }
window.location.href = uri + base64(template)