在nodejs中将excel文件转换为json

Converting excel file to json in nodejs

本文关键字:转换 json 文件 excel nodejs 中将      更新时间:2023-09-26

我正在尝试使用此 API 将 excel 文件转换为 json:转换 JSON 节点 API。

我可以在本地计算机上执行此操作,但不能在我的服务器上执行此操作。只有 csv 到 json 在本地和服务器上工作。这是我的代码:https://gist.github.com/debasreedash/33efd4473ba8b344a5ac

服务器在第一个控制台.log后立即尝试解析 excel 文件时崩溃。下面是它的样子:https://i.stack.imgur.com/2bAld.jpg

我认为这是服务器上没有 excel 驱动程序的问题,但在下载并安装后也不起作用。有人遇到过这个问题吗?如果您需要更多信息,请告诉我。

使用此方法可以轻松理解和解析:

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

专注于问题第一行的前半部分:如何将 Excel 转换为 json。

假设:Excel 电子表格是一个数据方块,其中第一行是对象键,其余行是对象值,所需的 json 是对象列表。

对之前答案的改进:删除不必要的拆分和连接(不必要的,如果键或值包含逗号,则可能导致无效转换),允许键中的点字符串暗示嵌套对象,coffeescript,写入文件。

虚线表示法:包含名字、姓氏、地址.街道、地址.城市、地址.州、地址.zip的键行 (0) 将每行生成一个带有名字和姓氏的文档和一个带有地址的嵌入式文档地址。

通过 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

找到适合我的快速准确的解决方案:

服务器.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');
    });
 

索引.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