koa上傳excel文件并解析的實(shí)現(xiàn)方法
更新時(shí)間:2018年08月09日 13:39:18 作者:小谷xg
這篇文章主要介紹了koa上傳excel文件并解析的實(shí)現(xiàn)方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
1.中間鍵使用 koa-body
npm install koa-body --save
const koaBody = require('koa-body'); app.use(koaBody({ multipart: true, formidable: { maxFileSize: 200 * 1024 * 1024 // 設(shè)置上傳文件大小最大限制,默認(rèn)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, '暫時(shí)不支持多個(gè)sheet存在'); } else { //得到的是數(shù)組 const objs = getRes.datas[0]; ctx.body = { status: true, msg: '上傳數(shù)據(jù)成功' }; } } else { errorResult.errorRes(ctx, getRes.msg); } await next(); }; module.exports = { saveData };
3.處理excel存儲(chǔ),解析,處理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); // 創(chuàng)建可讀流 const ext = file.name.split('.').pop(); // 獲取上傳文件擴(kuò)展名 const filePath = `${downPath}/${Math.random().toString()}.${ext}`; const upStream = fs.createWriteStream(filePath); // 創(chuàng)建可寫流 const getRes = await getFile(reader, upStream); //等待數(shù)據(jù)存儲(chǔ)完成 const datas = []; //可能存在多個(gè)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: '上傳文件錯(cuò)誤' }; } } function getFile (reader, upStream) { return new Promise(function (result) { let stream = reader.pipe(upStream); // 可讀流通過管道寫入可寫流 stream.on('finish', function (err) { result(err); }); }); } module.exports = { getExcelObjs };
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Nodejs把接收圖片base64格式保存為文件存儲(chǔ)到服務(wù)器上
這篇文章主要介紹了Nodejs把接收圖片base64格式保存為文件存儲(chǔ)到服務(wù)器上,文中代碼較簡短,需要的朋友可以參考下2018-09-09詳解nodejs微信公眾號(hào)開發(fā)——6.自定義菜單
這篇文章主要介紹了詳解nodejs微信公眾號(hào)開發(fā)——6.自定義菜單,自定義菜單能夠幫助公眾號(hào)豐富界面,讓用戶更好更快地理解公眾號(hào)的功能。2017-04-04Node.js?中常用內(nèi)置模塊(path?路徑模塊)
這篇文章主要介紹了Node.js?中常用內(nèi)置模塊(path?路徑模塊),文章圍繞主題展開詳細(xì)的相關(guān)介紹,具有一定的參考價(jià)值,感興趣的朋友可以參考一下2022-09-09