分享好友 编程语言首页 频道列表

用NODEJS处理EXCEL文件导入导出,文件上传

nodejs文章/教程  2023-02-09 05:250


參考文章

http://librajt.github.io/2013/08/04/handle-excel-file-with-nodejs/


对照了 ExcelJS , https://github.com/guyonroche/exceljs#create-a-workbook

node-xlsxhttps://github.com/mgcrea/node-xlsx

等 nodejs 等现有组件。决定使用node-xlsx


node-xlsx 基于现有前端强大组件 js-xlsx。 https://github.com/SheetJS/js-xlsx

简单使用样例:

var express = require('express');
var router = express.Router();
var xlsx = require('node-xlsx');
var fs = require('fs');

/* GET import excel test. */
router.get('/importExcel', function(req, res, next) {
 var filename='./public/test.xlsx';
 console.error(filename);
 // read from a file
var obj = xlsx.parse(filename);
console.log(JSON.stringify(obj));
 
res.send('import successfully!');
});
/* GET export excel test. */
router.get('/exportExcel', function(req, res, next) {
// write
var data = [[1,2,3],[true, false, null, 'sheetjs'],['foo','bar',new Date('2014-02-19T14:30Z'), '0.3'], ['baz', null, 'qux']];
var buffer = xlsx.build([{name: "mySheetName", data: data}]);
fs.writeFileSync('b.xlsx', buffer, 'binary');
res.send('export successfully!');

});


补充:

文件上传操作能够选择下面两种

fs                           https://github.com/jprichardson/node-fs-extra

formidable   https://github.com/felixge/node-formidable

上传參考代码1: http://www.tuicool.com/articles/F7JrMjj 

              https://cnodejs.org/topic/4f40a4dc0feaaa4424081758


上传文件  (记得创建上传文件的文件夹,比如public/upload )

routes/test.js

var formidable = require('formidable');
var http = require('http');
var util = require('util');
var express = require('express');
var fs = require('fs');
var path = require('path');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');

var app = express();
var server = http.createServer(app);

server.listen(3000);

app.set('views', '/views');
//app.use(favicon('/public/favicon.ico'));
app.use(bodyParser());
app.use('/public',express.static(path.join(__dirname, 'public')));


app.get('/',function(req, res) {

res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
});

app.post('/upload', function(req,res) {

 console.log(" ########## POST /upload ####### ");
    var fileTypeError = false;
    var target_path = __dirname+"/upload";
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.keepExtensions = true;
    form.maxFieldsSize = 10 * 1024 * 1024;
    form.uploadDir = target_path;

    var fields = [];
    var files = [];

    form.on('field', function (field, value) {
        fields.push([field, value]);
    });
    form.on('file', function (field, file) {
        console.log('upload file: ' + file.name);
       //推断文件类型是否是xlsx
        if (file.type != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
            fileTypeError = true;
        }
        files.push([field, file]);
    });

    form.on('end', function () {

        //遍历上传文件
        var fileName = '';
        var obj = '';
        var folder_exists = fs.existsSync(target_path);
        if (folder_exists) {
            var dirList = fs.readdirSync(target_path);
            dirList.forEach(function (item) {
                if (!fs.statSync(target_path + '/' + item).isDirectory()) {
                    console.log('parse item:' + target_path + '/' + item);
                    fileName = target_path + '/' + item;
                    if (!fileTypeError) {
                        //解析excel
                        obj = xlsx.parse(fileName);
                        console.log(JSON.stringify(obj));
                        //insert into DB
                        //todo
                        res.send({"rtnCode": "0", "rtnInfo": "成功导入数据"});
                    } else {
                        res.send({"rtnCode": "1", "rtnInfo": "文件格式不对"});
                    }
                    //delete file
                    fs.unlinkSync(fileName);

                }
            });
        }else{
            res.send({"rtnCode": "1", "rtnInfo": "系统错误"});
        }

    });
    form.on('error', function(err) {
        res.send({"rtnCode": "1", "rtnInfo": "上传出错"});
    });
    form.on('aborted', function() {
        res.send({"rtnCode": "1", "rtnInfo": "放弃上传"});
    });
    form.parse(req);
	
	
});






其它參考://返回上传进度


form.on('progress', function(bytesReceived, bytesExpected) {
  var progress = {
    type: 'progress',
    bytesReceived: bytesReceived,
    bytesExpected: bytesExpected
  };

  socket.broadcast(JSON.stringify(progress));
});


查看更多关于【nodejs文章/教程】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
打造自己的 nodejs 静态文件服务器(帖子内容,直接复制别人的)
用NodeJS打造你的静态文件服务器在《The Node Beginner Book》的中文版(http://nodebeginner.org/index-zh-cn.html)发布之后,获得国内的好评。也有同学觉得这本书略薄,没有包含进阶式的例子。@otakustay同学说:“确实,我的想法是在这之上补一个简单的MV

0评论2023-02-10548

NodeJS无所不能:细数10个令人惊讶的NodeJS开源项目
在几年的时间里,NodeJS逐渐发展成一个成熟的开发平台,吸引了许多开发者。有许多大型高流量网站都采用NodeJS进行开发,像PayPal,此外,开发人员还可以使用它来开发一些快速移动Web框架。  除了Web应用外,NodeJS也被应用在许多方面,本文盘点了NodeJS在其

0评论2023-02-10598

Linux环境下的Nodejs linux安装基本环境
最近在学习Node.js,在window下总是觉得不那么爽快。最简单而且环保的方法是在虚拟机中安装一个Linux。 { 1.Linux:家中的Linux为Centos。 2.VirtuallyBox: 开启2块网卡。第一个选Host-Only目的是为了让虚拟机通上网。第二块选Bridge Adapter,这是为了

0评论2023-02-09597

nodejs package.json说明
{"name": "test", //项目名称(必须),由小写英文字母、数字和下划线,不能含空格"version": "1.0.0", //项目版本(必须)"description": "This is for study gulp project !", //项目描述(必须)"homepage": "", //项目主页url " key

0评论2023-02-09473

017 nodejs取参四种方法req.body,req.params,req.param,req.body
摘要: nodejs取参四种方法req.body,req.params,req.param,req.body 获取请求很中的参数是每个web后台处理的必经之路,nodejs提供了四种方法来实现。获取请求很中的参数是每个web后台处理的必经之路,nodejs的 express框架 提供了四种方法来实现。req.bodyre

0评论2023-02-09446

nodejs查看本机hosts文件域名对应ip
const dns = require('dns')dns.lookup('domainName', function(err, result) {console.log(result)}) related:https://***.com/questions/36689536/how-to-resolve-hostname-to-an-ip-address-in-node-js

0评论2023-02-09475

nodejs工程拷贝后运行报module找不到问题
工程文件夹通过复制黏贴到另外一个地方,运行后报错 “can`t find module 某某某”,查看原因:输入node 进入控制台,输入console.log(module.paths)查看当前nodejs查找module的路径,如果没有工程里的node_modules,通过module.paths.push加入,检查是否有效

0评论2023-02-09947

C# Socket TCP Server & Client & nodejs client cctv5体育节目表
要调试公司某项目里的一个功能,因为要准备测试环境,趁这个机会重温了一下Socket(全还给老师了 -_-#),做个备份。C# Serverstatic void Main(string[] args){int port = 81;string host = "192.168.1.151";//创建终结点IPAddress ip = IPAddress.Parse(hos

0评论2023-02-09810

nodejs微信公众号快速开发|自定义关键字回复
一点说明:nodejs 微信api 扩展,集成大部分功能。案例https://github.com/leiroc/node-wxeasy-example 上传example中文件到服务器 ,然后 npm install 成功https://github.com/leiroc/node-wxeasy-exampleBUG and NEWS增加客户功能增加模板消息增加扫描带参数

0评论2023-02-09404

Centos 32位 安装 NodeJS
yum -y install gcc make gcc-c++ openssl-devel wget下载源码及解压:wget https://nodejs.org/dist/v6.9.5/node-v6.9.5.tar.gztar -zvxf node-v0.10.26.tar.gz编译及安装:cd node-v0.10.26 切换目录,执行./configuremakemake install验证是否安装配置成功

0评论2023-02-09537

nodejs一部分基本模块及作用 node 引入一个模块的过程是什么
收集了NodeJS开发中常用的一些模块。MVC框架 -ExpressExpress 是轻量灵活的Nodejs Web应用框架,它可以快速地搭建网站。Express框架建立在Nodejs内置的Http模块上,并对Http模块再包装,从而实际Web请求处理的功能。它支持多种前端模板,如Jade, EJS等。它是T

0评论2023-02-09868

nodejs定时启动程序 nodejs开机自启
npm install node-schedule# 或yarn add node-schedule使用(second、minute、hour、  date、dayOfWeek、month、year)每分钟第1秒执行一次const schedule = require("node-schedule");var rule = new schedule.RecurrenceRule();rule.second = 1;// 秒schedu

0评论2023-02-09406

更多推荐