node.js - 将 excel(.xlsx) 文件转换为 JSON

标签 node.js excel mongodb mongoose

我有一个名为 Sampledata.xlsx 的 Excel 工作表,我将其转换为 json 和 console.log 来打印此数据。

server.js


var xlsx2json = require('xlsx2json')


xlsx2json(
    'sampledata.xlsx',
{
    dataStartingRow: 2,
    mapping: {
        'name': 'B',//name
        'sku': 'C',//unit price            //sku
        'quantity': 'D',//quantity
        
    }
}).then(jsonArray => { 
    // [
    //     {"col_1": "Barton LCC", "col_2": "30", "col_3": "86.69"}
    // ]
    
//console.log(jsonArray);
});

this doc的帮助下。 我在这里想做的是,在我的 Sampledata.xlsx 文件中,我有更多数据,例如公寓、地址、价格等,我已经不知道我的 excel 工作表 中存在哪些字段,但我希望所有这些都是console.log。我怎么能做到这一点有什么办法可以做到这一点。

最佳答案

从“xlsx2json”导入xlsx2json;

        OR

const xlsx2json = require('xlsx2json');

const excel2json = [
(req, res, next) => {
xlsx2json(req.body.file.path)
  .then(result => result[0])
  .reduce((object, item, index) => {
     if (index === 0) {
      object.mapper = item;  // eslint-disable-line no-param-reassign
      return object;
     }
  const data = {};
  Object.keys(item).forEach((key) => {
    data[object.mapper[key]] = item[key];
  });
  object.data.push(data);
    return object;
 }, { mapper: {}, data: [] })
   .then(excel => console.log(excel)) // this gives json as output
   .catch(err => next(err));
 },
];

关于node.js - 将 excel(.xlsx) 文件转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47283126/

相关文章:

javascript - 生成 PDF 和 Excel 工作表,但在 Excel 中它既不打开也不选择保存....(就像在 Laravel 中一样)

node.js - 解析字符串(node js)。将数字数组查找到字符串中

email - nodejs、redis 和 mailparser 无法解析电子邮件

excel - 添加已安装和引用

vba - 如何超链接本地文件位置VBA

java - org.apache.poi 使​​用日期单元格创建 excel 工作簿

javascript - 使用node-postgres执行查询时,aws lambda不返回任何内容

javascript - 在node.js中使用外部json到jade

java - 如何将 mongodb 的连接对象提供给 JasperFillManager.fillReport() - Spring MongoDB Jasper Integration

javascript - Mongoose $inc 返回 "undefined is not a function"