在Node.js中将Excel文件转换为JSON

3
我正在尝试通过使用convert-json node api将Excel文件转换为json。 我能够在本地机器上完成此操作,但无法在服务器上完成。仅csv-to-json可以在本地和服务器上工作。这是我的代码:https://gist.github.com/debasreedash/33efd4473ba8b344a5ac。当尝试解析Excel文件时,服务器在第一个console.log之后崩溃。以下是它的样子:http://imgur.com/lzUy8sc。我认为这是服务器上没有Excel驱动程序的问题,但是下载并安装后仍未解决问题。有人遇到过这个问题吗?如果您需要更多信息,请让我知道。

请确保您的Excel文件没有被其他软件打开(尤其是Excel!)。 - Laurent Jalbert Simard
如果您的代码清单正确,且 console.log("Going to convert..."); 没有输出任何内容,则崩溃很可能发生在其他地方。尝试注释掉整个 try-catch 块,并确保第二个日志出现。 - SheetJS
4个回答

11

使用这种方法可以更轻松地理解和解析:

npm install --save excel'



var xls = require('excel');

xls('Sheet.xlsx', function(err, data) {
  if(err) throw err;
    // data is an array of arrays
});

正如它所说,返回的数据是一个数组的数组。我们希望它是JSON格式,这样就可以随心所欲地处理。

这是一个将数组转换为JSON的函数:

function convertToJSON(array) {
  var first = array[0].join()
  var headers = first.split(',');

  var jsonData = [];
  for ( var i = 1, length = array.length; i < length; i++ )
  {

    var myRow = array[i].join();
    var row = myRow.split(',');

    var data = {};
    for ( var x = 0; x < row.length; x++ )
    {
      data[headers[x]] = row[x];
    }
    jsonData.push(data);

  }
  return jsonData;
};

然后:

xlsx('tasks.xlsx', function(err,data) {
    if(err) throw err;
    //console.log(jsonDataArray(data));
    console.log(JSON.stringify(convertToJSON(data)));
    //console.log(data);
});

1
你应该注意到你正在使用的 excel 模块仅支持 .xlsx 文件。对于旧版本的支持,parse-xl 的效果非常好。 - user909694
如果某个列中的某个值已经包含逗号(,),则此操作将失败。它也会将其拆分并将该值附加到下一列。 您能否修复上面代码中的这个问题? - ani0710

2
专注于问题的第一行的前半部分:如何将Excel转换为json。
假设:Excel电子表格是一个数据方块,其中第一行是对象键,其余行是对象值,所需的json是对象列表。
改进之前的答案:删除不必要的分割和连接(不必要的,如果键或值包含逗号,则可能导致无效的转换),允许键中的点字符串表示嵌套对象,使用coffeescript编写文件。
点表示法:包含firstName、lastName、address.street、address.city、address.state、address.zip的键行(0)会产生一个文档,其中每行都有名字和姓氏,以及一个名为address的嵌入式文档,其中包含地址。
通过VisioN从如何在JavaScript中设置对象属性(对象属性)的字符串名称?分配函数。
首先,加载Excel模块。
npm install excel --save-dev

简单粗暴的代码,只为完成任务

fs = require 'fs'
excel = require 'excel'

FILES = [
  {src: 'input.xlsx', dst: 'output.json'}
  ]

# Assign values to dotted property names - set values on sub-objects
assign = (obj, key, value) ->
  # Because we recurse, a key may be a dotted string or a previously split
  # dotted string.
  key = key.split '.' unless typeof key is 'object'

  if key.length > 1
    e = key.shift()
    obj[e] = if Object.prototype.toString.call(obj[e]) is "[object Object]" then obj[e] else {}
    assign obj[e], key, value
  else
    obj[key[0]] = value

# The excel module reads sheet 0 from specified xlsx file
process = (src, dst) ->
  excel src, (err, data) ->
    throw err if err 

    keys = data[0]
    rows = data[1..]

    result = []
    for row in rows
      item = {}
      assign item, keys[index], value for value, index in row
      result.push item

    fs.writeFile dst, JSON.stringify(result, null, 2), (err) ->
      if err
        console.error("Error writing file #{dst}", err)
      else
        console.log "Updated #{dst}"

process file.src, file.dst for file in FILES

1

寻找适用于我的快速而精确的解决方案:

server.js

let express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    multer = require('multer'),
    crypto = require('crypto'),
    xlsxtojson = require('xlsx-to-json'),
    xlstojson = require("xls-to-json");
 
let fileExtension = require('file-extension');
 
    app.use(bodyParser.json());  
 
    let storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './input/')
        },
        filename: function (req, file, cb) {
            crypto.pseudoRandomBytes(16, function (err, raw) {
                cb(null, raw.toString('hex') + Date.now() + '.' + fileExtension(file.mimetype));
                });
        }
    });
 
    let upload = multer({storage: storage}).single('file');
 
    /** Method to handle the form submit */
    app.post('/sendFile', function(req, res) {
        let excel2json;
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:401,err_desc:err});
                 return;
            }
            if(!req.file){
                res.json({error_code:404,err_desc:"File not found!"});
                return;
            }
 
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                excel2json = xlsxtojson;
            } else {
                excel2json = xlstojson;
            }
 
           //  code to convert excel data to json  format
            excel2json({
                input: req.file.path,  
                output: "output/"+Date.now()+".json", // output json 
                lowerCaseHeaders:true
            }, function(err, result) {
                if(err) {
                  res.json(err);
                } else {
                  res.json(result);
                }
            });
 
        })
       
    });
    // load index file to upload file on http://localhost:3000/
    app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
    });
 
    app.listen('3000', function(){
        console.log('Server running on port 3000');
    });
 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Excel to Json in nodejs | jsonworld</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
 
<div class="jumbotron text-center">
    <h1>Excel to Json in nodejs</h1>
    <p>source : <a href="https://jsonworld.com">jsonworld</a></p> 
</div>
  
<div class="container">
    <div class="row">
        <div class="col-sm-4 col-md-offset-4">
            <form id="form" enctype ="multipart/form-data" action="sendFile" method="post">
            <div class="form-group">
            <input type="file" name="file" class="form-control"/>
            <input type="submit" value="Upload" name="submit" class="btn btn-primary" style="float:right; margin-top:30px;">
            </form>    
        </div>
    </div>
</div>
 
</body>
</html>

在此处查找更多信息:jsonworld


0
将文件单独上传,并使用convert-excel-to-json进行读取。
const result = excelToJson({
  sourceFile: 'public/files/initstock/' + file_name
});

结果将是一个表格行的数组
{ sheet1: [{ A: 'A1单元格的数据', B: 'B1单元格的数据', C: 'C1单元格的数据' }], sheet2: [{ A: 'A1单元格的数据', B: 'B1单元格的数据', C: 'C1单元格的数据' }] }
更多详情 - https://github.com/DiegoZoracKy/convert-excel-to-json

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接