纯前端通过dom导出excel
2021年1月20日·10 次阅读

纯前端通过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 =&gt; i &amp;&amp; i.trim());

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

const trarr = []

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

let theadHtml = ``
theadArr.map(e =&gt; {
  theadHtml += `&lt;th&gt;<span class="katex math inline">{e}&lt;/th&gt;`
})
let tbodyHtml = ``
trarr.forEach(tr =&gt; {
  let trHtml = `&lt;tr&gt;`
  tr.map(td =&gt; {
    trHtml += `&lt;td style="mso-number-format:'\@'"&gt;</span>{td}&lt;/td&gt;`
  })
  tbodyHtml += trHtml + `&lt;/tr&gt;`
})


const table = `&lt;table&gt;&lt;thead&gt;&lt;tr&gt;<span class="katex math inline">{theadHtml}&lt;/tr&gt;&lt;/thead&gt; &lt;tbody&gt;</span>{tbodyHtml}&lt;/tbody&gt;&lt;/table&gt;`
// console.log(table);


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

}

导出效果

> cd ..