nodejs读取xlsx文件

2021-06-17 11:02

阅读:515

标签:data   erro   ssi   stat   doc   log   cas   strong   name   

依赖包:multiparty,XLSX,代码如下:

var multiparty = require(‘multiparty‘);
var XLSX = require("xlsx");
var form = new multiparty.Form();

function to_json(workbook,id){
    // 获取 Excel 中所有表名,返回 [‘sheet1‘, ‘sheet2‘]
    var sheetNames = workbook.SheetNames;
    sheetNames.forEach(function(sheetName) {
        //获取每个sheet的数据。
        var worksheet = workbook.Sheets[sheetName];
        var tempArray = XLSX.utils.sheet_to_json(worksheet);
        tempArray.forEach(function(ele){
            //获取每一条记录
            ele.state = ele.state || 0;
            ele.create_time = ele.modify_time = utils.formatDate();
            ele.modify_user = username;
        });
        result[sheetName] = tempArray;
    }); 
    // 把所有数据都已经读取到内存中去了
    return result; 
}
form.parse(req, function(err, fields, files) {
    if(err){
        throw new Error("form is error");
    }
    /*{
    "fileToUpload": [
        {
            "fieldName": "fileToUpload",
            "originalFilename": "test.xlsx",
            "path": "/var/folders/tk/jwcqj5_x74lgdzfcdhv248x00000gn/T/TILXemNkWT5V2YoNDXpxnEeS.xlsx",
            "headers": {
                "content-disposition": "form-data; name=\"fileToUpload\"; filename=\"test.xlsx\"",
                "content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            },
            "size": 9389
        }
        ]
    } 
    */
    var filename = files.fileToUpload[0].originalFilename;
    var suffixArray = filename.split(‘.‘);
    var suffix = suffixArray[suffixArray.length - 1].toLowerCase();
    if( suffix != "xlsx" && suffix != "xls"){
        throw new Error("只能上传xlsx,xls格式的文件");
    }else{
        //服务器临时储存文件的路径
        var filepath = files.fileToUpload[0].path;
        console.log("读取的xlsx文件路径为:"+filepath);
        var workbook = XLSX.readFile(filepath);
        var result = to_json(workbook,req.session.login_username);
        //删除服务器临时储存文件的路径
        fs.unlink(filepath,function(err){
            console.error(filepath + "文件删除失败!"+err);
        });
    }
});

 

nodejs读取xlsx文件

标签:data   erro   ssi   stat   doc   log   cas   strong   name   

原文地址:http://www.cnblogs.com/liuyinlei/p/7267040.html


评论


亲,登录后才可以留言!