zoukankan      html  css  js  c++  java
  • 使用 xlsx 前端解析 excel 文件

    首先安装 xlsx

    npm install xlsx

    项目中引入

    import XLSX from 'xlsx';

    上传组件,因为懒得写样式,这里使用的 antd 的 Upload 组件,使用 <input type="file" /> 也是可以的。

    使用 customRequest 自定义上传

                    <Upload
                        name="file"
                        accept=".xls,.xlsx"
                        showUploadList={false}
                        customRequest={upload}
                    >
                        <span className={cns(style.btn, style.import)}>
                            <img src={importPNG}/>
                            <span>导入数据</span>
                        </span>
                    </Upload>

    核心代码,解析 excel

        const upload = (e) => {
            const f = e.file;
            const reader = new FileReader();  // 使用 FileReader 读取数据
            reader.onload = function(e) {  // 数据读取完成后的回调函数
              const data = new Uint8Array(e.target.result);
              const workbook = XLSX.read(data, {type: 'array'});  // workbook 是 xlsx 解析 excel 后返回的对象
          
              const firstSheetName = workbook.SheetNames[0];  // 获取第一个 sheet 的名字
              const worksheet = workbook.Sheets[firstSheetName];  // 获取第一个 sheet 的内容
              const res = XLSX.utils.sheet_to_json(worksheet);  // 使用 utils 里的方法转换内容为便于使用的数组
    
              // 下面就是自己对数组进行操作就行了
              const list = res.map(item => {
                  return {
                      keyword: item.keyword,
                      weight: item.weight
                  }
              });
              
              wordObj.setKeys([...wordObj.keys, ...list]);
            };
            reader.readAsArrayBuffer(f);  // 读取数据
        };

  • 相关阅读:
    echarts图例全选功能实现
    前端面试基础整理(一)
    echarts自定义折线图横坐标时间间隔踩坑总结
    快应用开发总结
    vue3.0学习笔记(一)
    完整开发vue后台管理系统小结
    多状态组件封装有感
    vue容易混淆的点小记
    h5定位geolaction无法调试解决方法
    Mysql数据库主从心得整理
  • 原文地址:https://www.cnblogs.com/3body/p/12309438.html
Copyright © 2011-2022 走看看