zoukankan      html  css  js  c++  java
  • 用NODEJS处理EXCEL文件导入导出,文件上传


    參考文章

    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));
    });


  • 相关阅读:
    Decimal、 Float、 Double 使用
    jdk1.7的collections.sort(List list)排序问题
    $watch、$digest、$apply
    BeanNameViewResolver
    This system is not registered with RHN
    JNI字段描述符-Java Native Interface Field Descriptors
    服务器端cs文件
    ASP.NET基础(一)
    Android开发日记(七)
    登陆 注册
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/6768763.html
Copyright © 2011-2022 走看看