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の書き方
upoloadData.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を処理して保存し、解析し、エクセルを処理するためのライブラリはxlsxです。

npm install xlsx --save
upoloadExcel Srv.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
};

以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。