json文件转换xlsx文件(Nodejs)

nodejs_npm

 

前言

实现xls与json格式互转,推荐结合阅读:

excel文件转换json文件(nodejs|python)

正文

使用插件:json2xls

官方页有简单的示例,在此基础上扩展为转换指定的json文件。

GitHub:

https://github.com/pury/SPTools/tree/master/json2xls

var fs = require("fs");
var json2xls = require('json2xls');
var args = process.argv.splice(2);

if (args && args.length)
{
  var file = args[0];
  fs.readFile(file, "utf8", (err, data) => {

    if (err)
    {
      throw err;	
    }

    try
    {
      var jsonData = JSON.parse(data);	
      var xls = json2xls(jsonData);
      var fileName = file.split(".")[0];
      fs.writeFileSync(fileName + ".xlsx", xls, "binary");
      console.log("Success!");
    }
    catch (e)
    {
      throw e;	
    }
  });
}
else
{
  console.log("Please input a file name");
}

使用方法

$ npm install json2xls
$ node go.js 文件名

注意

excel文件为二维表单,json对象应为符合插件要求的格式,可视为元素为对象的一维数组,如果不符合要求,需要自行转换。

[
{"id":1001,"name":"tom","level":23,"brief":"I am tom"},	
{"id":1002,"name":"pub","level":33,"brief":"I am pub"},	
{"id":1003,"name":"acu","level":43,"brief":"I am acu"},	
{"id":1004,"name":"foo","level":23,"brief":"I am foo"},	
{"id":1005,"name":"coo","level":54,"brief":"I am coo"}
]

By Pury.