js-excel in html

2024-06-30  本文已影响0人  xueyueshuai

html中

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Download Excel in HTML</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.2/xlsx.full.min.js"></script>
</head>
<body>
  <form>
    <input type="file" id="excelFile" accept=".xlsx, .xls" />
    <input type="button" value="Read Excel" onclick="readExcel()" />
  </form>

  <div id="excelContent"></div>

  <button onclick="downloadExcel()">Download Excel</button>


  <script>

    function readExcel() {
      var fileInput = document.getElementById('excelFile');
      var excelContentDiv = document.getElementById('excelContent');

      var file = fileInput.files[0];
      var reader = new FileReader();

      reader.onload = function (e) {
        var data = new Uint8Array(e.target.result);
        var workbook = XLSX.read(data, { type: 'array' });
        var sheetName = workbook.SheetNames[0];
        var sheet = workbook.Sheets[sheetName];

        var excelData = null;
        excelData = XLSX.utils.sheet_to_json(sheet, { header: 0 });
        // excelData = XLSX.utils.sheet_to_json(sheet, { header: 1 });
        console.log(excelData)

        excelContentDiv.innerHTML = JSON.stringify(excelData);
      };

      reader.readAsArrayBuffer(file);
    }

    function downloadExcel() {
      let exportExcelData = [[1,1],[22,2222]];
      if (exportExcelData) {
        let ws = XLSX.utils.aoa_to_sheet(exportExcelData);
        let wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Sheet 1");
        XLSX.writeFile(wb, '1.xlsx');
      } else {
        alert("No Excel data available. Please upload an Excel file first.");
      }
    }
  </script>
</body>
</html>

上一篇下一篇

猜你喜欢

热点阅读