前端将JSON或者table直接导出为excel

时间:2024-10-13 07:26:40

一、引入Sheetjs或者npm直接下载

<script lang="javascript" src="https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js"></script>

二、页面中使用

//json导出为excel
<button onclick="exportExcel()">导出</button>
  <script>
    const exportExcel = () => {
      const data = [
        { name: 'John', age: 30, city: 'New York' },
        { name: 'Anna', age: 22, city: 'London' }
      ];

      const fields = ['name', 'age', 'city'];
      var workbook = XLSX.utils.book_new();
      const worksheet = XLSX.utils.json_to_sheet(data, { header: fields });
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
      XLSX.writeFile(workbook, 'data.xlsx');
    }
  </script>
//表格table转成excel
//result 是table的id
 const wb = XLSX.utils.table_to_book(document.getElementById('result'))
  XLSX.writeFile(wb, 'location.xlsx')