在nodejs中将excel文件转换为json [英] Converting excel file to json in nodejs

查看:555
本文介绍了在nodejs中将excel文件转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此api将excel文件转换为json:
convert-json node api。

I am trying to convert an excel file to json by using this api: convert-json node api.

我能够在我的本地机器,但不在我的服务器上。只有csv-to-json在本地和服务器上运行。这是我的代码:
https://gist.github.com/debasreedash/33efd4473ba8b344a5ac

I am able to do it on my local machine but not on my server. Only the csv-to-json works locally and on the server. Here is my code: https://gist.github.com/debasreedash/33efd4473ba8b344a5ac

尝试在第一个console.log之后立即解析excel文件时,服务器崩溃。以下是它的样子:
http://imgur.com/lzUy8sc

The server crashes while trying to parse the excel file right after the first console.log. Here is what it looks like: http://imgur.com/lzUy8sc

我认为这是一个问题,在服务器上没有excel驱动程序,但下载和安装后它也无法正常工作。有人遇到过这个问题吗?如果您需要更多信息,请告诉我。

I thought that it was a problem with not having excel drivers on the server but after downloading and installing it did not work either. Has anyone come across this issue? If you need anymore information then let me know.

推荐答案

使用此方法可以轻松取消记录和解析:

Use this method for easy undertsanding and parsing :

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,以便我们可以随心所欲地使用它。

As it says, the data it returns is an array of arrays. We want it to be JSON, so that we can do whatever we want with it.

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

This is a function that converts an array of arrays to 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);
});

这篇关于在nodejs中将excel文件转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆