纯前端通过dom导出excel

纯前端通过dom导出excel

插件file-saver

npm i file-saver

js部分(要求列表html有常规的table完整标签)
例如:

<table>
  <thead>
    <tr>
      <th>姓名</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>张三</td>
    </tr>
  </tbody>
</table>
exportExel() {
    // excel取名
   // const tableName= '列表';

    const thead = document.getElementsByTagName("thead");
    const theade = thead[0].innerText

    const theadArr = theade.split(/\n/).filter(i => i && i.trim());

    const tr = document.querySelectorAll('tbody tr')

    const trarr = []

    if (theadArr[theadArr.length - 1].includes('操作')) {
      theadArr.pop()
      tr.forEach((e: any, i) => {
        trarr.push(e.innerText.split('\t').slice(0, -1));
      })
    } else {
      tr.forEach((e: any, i) => {
        trarr.push(e.innerText.split('\t'));
      })
    }

    let theadHtml = ``
    theadArr.map(e => {
      theadHtml += `<th>{e}</th>`
    })
    let tbodyHtml = ``
    trarr.forEach(tr => {
      let trHtml = `<tr>`
      tr.map(td => {
        trHtml += `<td style="mso-number-format:'\@'">{td}</td>`
      })
      tbodyHtml += trHtml + `</tr>`
    })


    const table = `<table><thead><tr>{theadHtml}</tr></thead> <tbody>{tbodyHtml}</tbody></table>`
    // console.log(table);


    const blob = new Blob([table], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
    });
    saveAs(blob, `${tableName}.xlsx`);
  }

导出效果

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注