XLSX + LuckySheet + LuckyExcel + Web Worker实现前端的excel预览

功能简介

  1. 通过LuckyExcel的transformExcelToLucky方法, 我们可以把一个文件直接转成LuckySheet需要的json字符串, 之后我们就可以用LuckySheet预览excel
  2. LuckyExcel只能解析xlsx格式的excel文件,因此对于xls和csv的格式,我们需要通过XLSX来转化成xlsx格式,但在转化过程中会丢失样式
  3. 对于excel中存在很多的空白行,在显示的时候可能会出现卡顿,所以我们需要将过多的空白行移除

简单代码实现

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Excel File Upload and Preview with Luckysheet</title>
</head>
<body>

<!-- 文件上传控件 -->
<input type="file" id="fileUpload"/>

<!-- Luckysheet 的容器 -->
<div id="luckysheet" style="position: relative; width: 100%; height: 500px;"></div>
<script src="https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js"></script>

<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/plugins/css/pluginsCss.css'/>
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/plugins/plugins.css'/>
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/css/luckysheet.css'/>
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/assets/iconfont/iconfont.css'/>
<script src="https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/plugins/js/plugin.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/luckysheet.umd.js"></script>


<script src="https://cdn.jsdelivr.net/npm/luckyexcel/dist/luckyexcel.umd.js"></script>

<script>
 
 const _xlsxType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const  _xlsType = 'application/vnd.ms-excel';
  const  _csvType = 'text/csv';

  //如果后端是以流的方式返回,可以调用这个方法
  const handleExcel = (res, fileName) => {
    const file = getExcelFile(res, fileName);
    handleExcelFile(file);
  }


 // 获取Excel文件
  const getExcelFile = (res, fileName) => {
  // 根据文件后缀名判断文件类型
    if (fileName.endsWith('.xlsx')) {
      return new File([res], fileName, {type: _xlsxType});
    } else if (fileName.endsWith('.xls')) {
      return new File([res], fileName, {type: _xlsType});
    } else if (fileName.endsWith('.csv')) {
      return new File([res], fileName, {type: _csvType});
    } else {
      throw new Error("Unsupported file type");
    }
  }
  
	// 处理Excel文件
  const handleExcelFile = (file) => {
    const fileName = file.name;
    // 根据文件后缀名判断文件类型并进行处理
    if (fileName.endsWith('.xlsx')) {
      console.log("handle excel for xlsx type..", fileName);
      handleExcelForXlsxType(file, fileName);
    } else if (fileName.endsWith('.xls') || fileName.endsWith('.csv')) {
      console.log("handle excel for xls or csv type..", fileName);
      handleExcelForXlsAndCsvType(file, fileName);
    } else {
      throw new Error("Unsupported file type");
    }
  }

// 处理xlsx类型的Excel文件
  const handleExcelForXlsxType = (file, fileName) => {
    const reader = new FileReader();
    reader.onload = function (event) {
      const data = new Uint8Array(event.target.result);
      const workbook = XLSX.read(data, {type: 'array'});
       // 获取Excel文件中的最大行数
      let maxRowCountFromExcel = getMaxRowCountFromExcel(workbook);
      // 如果行数大于100000,则处理Excel文件中的空行
      if (maxRowCountFromExcel > 1000000) {
        console.log("excel file has too many blank row..", maxRowCountFromExcel);
        handleBlankRowForExcelWithTooManyBlankRow(workbook);
        const xlsxFile = toXlsxExcelFile(workbook, fileName);
        createLuckySheet(xlsxFile);
      } else {
        createLuckySheet(file);
      }
    };
    reader.readAsArrayBuffer(file);
  }

// 处理xls和csv类型的Excel文件
  const handleExcelForXlsAndCsvType = (file, fileName) => {
    const reader = new FileReader();
     // 读取文件完成后的回调函数
    reader.onload = function (event) {
      const data = new Uint8Array(event.target.result);
        // 读取Excel文件内容
      const workbook = XLSX.read(data, {type: 'array'});
       // 将Excel文件转换为xlsx类型
      const xlsxFile = toXlsxExcelFile(workbook, fileName);
       // 处理xlsx类型的Excel文件
      handleExcelForXlsxType(xlsxFile, fileName);
    };
    // 以ArrayBuffer的形式读取文件
    reader.readAsArrayBuffer(file);
  }

/ 创建Luckysheet
  const createLuckySheet = (file) => {
  // 销毁已存在的Luckysheet
    window.luckysheet.destroy();
     // 将Excel文件转换为Luckysheet的json
    LuckyExcel.transformExcelToLucky(file, function (exportJson, luckysheetfile) {
      if (exportJson.sheets == null || exportJson.sheets.length === 0) {
        throw new Error("Failed to load excel file");
      }
      // 创建Luckysheet的配置项
      const options = {
        container: 'luckysheet',
        data: exportJson.sheets, // title: exportJson.info.name,
        // userInfo: exportJson.info.name.creator,
        column: 10,
        row: 10,
        showinfobar: false,
        sheetFormulaBar: true,
        showConfigWindowResize: false
      };
      // 创建Luckysheet
      window.luckysheet.create(options);
    });
  }
  // 获取Excel文件中的最大行数
  const getMaxRowCountFromExcel = (workbook) => {
    let maxRowCount = 0;
    if (workbook.SheetNames == null || workbook.SheetNames.length === 0) {
      return maxRowCount;
    }
    // 遍历每个sheet,获取最大行数
    workbook.SheetNames.forEach(sheetName => {
      const worksheet = workbook.Sheets[sheetName];
      if (worksheet['!ref'] === undefined) {
        return;
      }
      const range = XLSX.utils.decode_range(worksheet['!ref']);
      maxRowCount = maxRowCount + range.e.r;
    });
	console.log("max:", maxRowCount)
    return maxRowCount;
  }
  const reduceBlankRow = (row, range, worksheet) => {
   // 从给定的行开始,向上遍历到工作表的起始行
    while (row > range.s.r) {
     // 假设当前行是空的
      let allEmpty = true;
       // 遍历当前行的所有列
      for (let col = range.s.c; col <= range.e.c; col++) {
      // 获取当前单元格的引用
        const cell_ref = XLSX.utils.encode_cell({c: col, r: row});
         // 如果当前单元格不为空,则将allEmpty设置为false并跳出循环
        if (worksheet[cell_ref]) {
          allEmpty = false;
          break;
        }
      }
      // 如果当前行是空的,则将行数减一,否则跳出循环
      if (allEmpty) {
        row--;
      } else {
        break;
      }
    }
     // 更新工作表范围的结束行
    range.e.r = row;
     // 更新工作表的范围引用
    worksheet['!ref'] = XLSX.utils.encode_range(range.s, range.e);
  }
  // 处理Excel文件中的空行
  const handleBlankRowForExcelWithTooManyBlankRow = (workbook) => {
    if (workbook.SheetNames == null || workbook.SheetNames.length === 0) {
      return;
    }
     // 遍历每个sheet,处理空行
    workbook.SheetNames.forEach(sheetName => {
      const worksheet = workbook.Sheets[sheetName];
      if (worksheet['!ref'] === undefined) {
        return;
      }
      const range = XLSX.utils.decode_range(worksheet['!ref']);
      let row = range.e.r;
      reduceBlankRow(row, range, worksheet);
    });
  }
	// 将Excel文件转换为xlsx类型
  const toXlsxExcelFile = (workbook, fileName) => {
    const newWorkbook = XLSX.write(workbook, {bookType: 'xlsx', type: 'binary'});
    const data = new Uint8Array(newWorkbook.length);
    for (let i = 0; i < newWorkbook.length; i++) {
      data[i] = newWorkbook.charCodeAt(i);
    }
    return new File([data], fileName, {type: _xlsxType});
  }


 // 文件上传控件的change事件处理函数
  document.getElementById('fileUpload').addEventListener('change', function (e) {
 	 // 获取上传的文件
    const file = e.target.files[0];
     // 处理Excel文件
    handleExcelFile(file);

  });




</script>

</body>
</html>

web worker 版本

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Excel File Upload and Preview with Luckysheet</title>
</head>
<body>

<!-- 文件上传控件 -->
<input type="file" id="fileUpload"/>

<!-- Luckysheet 的容器 -->
<div id="luckysheet" style="position: relative; width: 100%; height: 500px;"></div>
<div id="worker" style="display:none">


  importScripts("https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js")
  const _xlsxType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const _xlsType = 'application/vnd.ms-excel';
  const _csvType = 'text/csv';
  const _maxRowCount = 5000000;


  self.addEventListener('message', (e) => {
  console.log('Worker get message:', e.data)
  handleExcel(e.data.data, e.data.fileName)
  });


  const handleExcel = (res, fileName) => {
  const file = getExcelFile(res, fileName);
  handleExcelFile(file);
  }

  const getExcelFile = (res, fileName) => {
  if (fileName.endsWith('.xlsx')) {
  return new File([res], fileName, {type: _xlsxType});
  } else if (fileName.endsWith('.xls')) {
  return new File([res], fileName, {type: _xlsType});
  } else if (fileName.endsWith('.csv')) {
  return new File([res], fileName, {type: _csvType});
  } else {
  throw new Error("Unsupported file type");
  }
  }

  const handleExcelFile = (file) => {
  const fileName = file.name;
  if (fileName.endsWith('.xlsx')) {
  console.log("handle excel for xlsx type..", fileName);
  handleExcelForXlsxType(file, fileName);
  } else if (fileName.endsWith('.xls') || fileName.endsWith('.csv')) {
  console.log("handle excel for xls or csv type..", fileName);
  handleExcelForXlsAndCsvType(file, fileName);
  } else {
  throw new Error("Unsupported file type");
  }
  }

  const handleExcelForXlsxType = (file, fileName) => {
  const reader = new FileReader();
  reader.onload = function (event) {
  const data = new Uint8Array(event.target.result);
  const workbook = XLSX.read(data, {type: 'array', cellDates: true});
  let maxRowCountFromExcel = getMaxRowCountFromExcel(workbook);
  if (maxRowCountFromExcel > _maxRowCount) {
  console.log("excel file has too many blank row..", maxRowCountFromExcel);
  handleBlankRowForExcelWithTooManyBlankRow(workbook);
  const xlsxFile = toXlsxExcelFile(workbook, fileName);
  createLuckySheet(xlsxFile);
  } else {
  createLuckySheet(file);
  }
  };
  reader.readAsArrayBuffer(file);
  }

  const handleExcelForXlsAndCsvType = (file, fileName) => {
  const reader = new FileReader();
  reader.onload = function (event) {
  const data = new Uint8Array(event.target.result);
  const workbook = XLSX.read(data, {type: 'array', cellDates: true});
  let maxRowCountFromExcel = getMaxRowCountFromExcel(workbook);
  if (maxRowCountFromExcel > _maxRowCount) {
  console.log("excel file has too many blank row..", maxRowCountFromExcel);
  handleBlankRowForExcelWithTooManyBlankRow(workbook);
  }
  const xlsxFile = toXlsxExcelFile(workbook, fileName);
  handleExcelForXlsxType(xlsxFile, fileName);
  };
  reader.readAsArrayBuffer(file);
  }

  const createLuckySheet = (file) => {
  const reader = new FileReader();
  reader.onload = (event => {
  postMessage({
  fileArrayBuffer: event.target.result ,
  fileName: file.name,
  })
  });
  reader.readAsArrayBuffer(file);

  }
  const getMaxRowCountFromExcel = (workbook) => {
  let maxRowCount = 0;
  if (workbook.SheetNames == null || workbook.SheetNames.length === 0) {
  return maxRowCount;
  }
  workbook.SheetNames.forEach(sheetName => {
  const worksheet = workbook.Sheets[sheetName];
  if (worksheet['!ref'] === undefined) {
  return;
  }
  const range = XLSX.utils.decode_range(worksheet['!ref']);
  maxRowCount = maxRowCount + range.e.r;
  });
  return maxRowCount;
  }
  const reduceBlankRow = (row, range, worksheet) => {
  while (row > range.s.r) {
  let allEmpty = true;
  for (let col = range.s.c; col <= range.e.c; col++) {
  const cell_ref = XLSX.utils.encode_cell({c: col, r: row});
  if (worksheet[cell_ref]) {
  allEmpty = false;
  break;
  }
  }
  if (allEmpty) {
  row--;
  } else {
  break;
  }
  }
  range.e.r = row;
  worksheet['!ref'] = XLSX.utils.encode_range(range.s, range.e);
  }
  const handleBlankRowForExcelWithTooManyBlankRow = (workbook) => {
  if (workbook.SheetNames == null || workbook.SheetNames.length === 0) {
  return;
  }
  workbook.SheetNames.forEach(sheetName => {
  const worksheet = workbook.Sheets[sheetName];
  if (worksheet['!ref'] === undefined) {
  return;
  }
  const range = XLSX.utils.decode_range(worksheet['!ref']);
  let row = range.e.r;
  reduceBlankRow(row, range, worksheet);
  });
  }

  const toXlsxExcelFile = (workbook, fileName) => {
  const newWorkbook = XLSX.write(workbook, {bookType: 'xlsx', type: 'binary'});
  const data = new Uint8Array(newWorkbook.length);
  for (let i = 0; i < newWorkbook.length; i++) {
  data[i] = newWorkbook.charCodeAt(i);
  }
  return new File([data], fileName, {type: _xlsxType});
  }


  self.addEventListener('error', function (event) {
  console.log("test....................", event)
  });


</div>
<script src="https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js"></script>

<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/plugins/css/pluginsCss.css'/>
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/plugins/plugins.css'/>
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/css/luckysheet.css'/>
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/assets/iconfont/iconfont.css'/>
<script src="https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/plugins/js/plugin.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/luckysheet.umd.js"></script>


<script src="https://cdn.jsdelivr.net/npm/luckyexcel/dist/luckyexcel.umd.js"></script>

<script>


  const createLuckySheet = (exportJson) => {
    console.log(exportJson)
    window.luckysheet.destroy();
    const options = {
      container: 'luckysheet',
      data: exportJson.sheets, // title: exportJson.info.name,
      // userInfo: exportJson.info.name.creator,
      column: 10,
      row: 10,
      showinfobar: false,
      sheetFormulaBar: true,
      showConfigWindowResize: false
    };
    window.luckysheet.create(options);

  }

  const createLuckySheetByFileArrayBuffer = (arrayBuffer, fileName) => {
    const xlsxTtpe = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    const file = new File([arrayBuffer], fileName, {type: xlsxTtpe});
    LuckyExcel.transformExcelToLucky(file, function (exportJson, luckysheetfile) {
      createLuckySheet(exportJson);
    });
  }

  var blob = new Blob([document.querySelector('#worker').textContent]);
  var url = window.URL.createObjectURL(blob);
  var worker = new Worker(url);
  worker.addEventListener('message', (event) => {
    const data = event.data
    createLuckySheetByFileArrayBuffer(data.fileArrayBuffer, data.fileName)

  })

  document.getElementById('fileUpload').addEventListener('change', function (e) {
    const file = e.target.files[0];

    const reader = new FileReader();
    reader.onload = (event => {
      worker.postMessage({
        data: event.target.result,
        fileName: file.name
      })
    });
    reader.readAsArrayBuffer(file);

  });


</script>

</body>
</html>

效果

在这里插入图片描述

参考

https://juejin.cn/post/7211805251216031801
https://segmentfault.com/a/1190000043720845
https://juejin.cn/post/7232524757525659708
https://blog.csdn.net/q2qwert/article/details/130908294
https://www.cnblogs.com/ajaemp/p/12880847.html
https://blog.csdn.net/weixin_40775791/article/details/135409716
https://blog.csdn.net/u013113491/article/details/129106671

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
qtxlsx 是一个用于在 Qt 框架中读写 Excel 文件的开源库,而 Qt Creator 则是一个用于开发 Qt 应用程序的集成开发环境(IDE)。在这里,我将介绍一个用 qtxlsx 和 Qt Creator 编写的操作 Excel 文件的小案例。 首先,我们需要在 Qt Creator 中创建一个新的 Qt 应用程序项目。在项目文件中引入 qtxlsx 库,并在.pro 文件中添加相关的库依赖。 然后,在主窗口中添加一个按钮和一个编辑框。按钮的功能是选择 Excel 文件并读取其中的内容,编辑框用于显示读取到的内容。 接下来,我们要使用 qtxlsx 进行 Excel 文件操作。为了实现这个目标,我们需要导入相应的头文件,并在按钮的点击事件中添加相关代码。在这个案例中,我们将选择一个 Excel 文件,并将其内容读取到一个 QStringList 对象中。然后,我们将 QStringList 对象中的内容显示在编辑框中。 为了实现这个功能,我们需要先创建一个 QXlsx::Document 对象,然后使用 `load()` 方法加载 Excel 文件。接着,我们使用 `sheetNames()` 方法获取 Excel 文件中的所有工作表名称,并使用 `read()` 方法读取指定工作表的内容。最后,将读取到的内容保存在 QStringList 对象中,并显示在编辑框中。 当用户点击按钮后,会触发一个信号,我们将创建的槽函数将在按钮点击事件发生时被调用,实现 Excel 文件的读取。当从 Excel 文件中读取内容后,我们可以根据需要对数据进行进一步的操作,比如进行计算、筛选等。 以上就是使用 qtxlsx 和 Qt Creator 编写的对 Excel 文件进行操作的小案例。通过这个案例,我们可以学习如何使用 qtxlsx 库读取 Excel 文件的内容,并在 Qt Creator 中进行相关的操作。这样的小案例可以帮助我们更好地理解和掌握 qtxlsx 和 Qt Creator 的使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值