zoukankan      html  css  js  c++  java
  • koa上传excel文件并解析

    1.中间键使用 koa-body

    
    npm install koa-body --save
    
    
    const koaBody = require('koa-body');
    
    app.use(koaBody({
      multipart: true,
      formidable: {
        maxFileSize: 200 * 1024 * 1024 // 设置上传文件大小最大限制,默认2M
      }
    }));
    

    2.书写路由,croller书写方法
    uploadData.js

    
    const errorResult = require('../utils/errorResult.js');
    const uploadExcelSrv = require('../service/uploadExcelSrv');
    
    const saveData = async function (ctx, next) {
    
      const getRes = await uploadExcelSrv.getExcelObjs(ctx);
      if (getRes.status) {
        if (getRes.datas.length > 1) {
          errorResult.errorRes(ctx, '暂时不支持多个sheet存在');
        } else { //得到的是数组
          const objs = getRes.datas[0];
          ctx.body = {
            status: true,
            msg: '上传数据成功'
          };
        }
      } else {
        errorResult.errorRes(ctx, getRes.msg);
      }
      await next();
    };
    module.exports = {
      saveData
    };
    

    3.处理excel存储,解析,处理excel用的库是 xlsx

    
    npm install xlsx --save
    

    uploadExcelSrv.js

    
    //接收上传的excel文件,保存解析返回objects
    const xlsx = require('xlsx');
    const fs = require('fs');
    const path = require('path');
    const downPath = path.resolve(__dirname, '../../fileUpload');
    
    async function getExcelObjs (ctx) {
      const file = ctx.request.files.file; // 获取上传文件
      const reader = fs.createReadStream(file.path); // 创建可读流
      const ext = file.name.split('.').pop(); // 获取上传文件扩展名
      const filePath = `${downPath}/${Math.random().toString()}.${ext}`;
    
      const upStream = fs.createWriteStream(filePath); // 创建可写流
      const getRes = await getFile(reader, upStream); //等待数据存储完成
    
      const datas = []; //可能存在多个sheet的情况
      if (!getRes) { //没有问题
        const workbook = xlsx.readFile(filePath);
        const sheetNames = workbook.SheetNames; // 返回 ['sheet1', ...]
        for (const sheetName of sheetNames) {
          const worksheet = workbook.Sheets[sheetName];
          const data = xlsx.utils.sheet_to_json(worksheet);
          datas.push(data);
        }
        return {
          status: true,
          datas
        };
      } else {
        return {
          status: false,
          msg: '上传文件错误'
        };
      }
    }
    
    function getFile (reader, upStream) {
      return new Promise(function (result) {
        let stream = reader.pipe(upStream); // 可读流通过管道写入可写流
        stream.on('finish', function (err) {
          result(err);
        });
      });
    }
    module.exports = {
      getExcelObjs
    };
    

    来源:https://segmentfault.com/a/1190000015943339

  • 相关阅读:
    PHP数组的几个操作,求并集,交集,差集,数组与字符串的相互转换及数组去重
    文件系统添加链接
    HTML中插入视频
    magento模块的建立
    数组函数
    字符串函数
    阿里服务器用户的添加
    ViewChild
    GitHub 图片加载不出来怎么办
    常用正则表达式
  • 原文地址:https://www.cnblogs.com/lovellll/p/10180073.html
Copyright © 2011-2022 走看看