使用Node解析XLSX并创建json

好的,所以我发现这个文档很好地node_module称为js-xlsx

如何 ?

这是excel工作表的样子:

在此处输入图片说明

最后,json应该看起来像这样:

[

{

"id": 1,

"Headline": "Team: Sally Pearson",

"Location": "Austrailia",

"BodyText": "...",

"Media: "..."

},

{

"id": 2,

"Headline": "Team: Rebeca Andrade",

"Location": "Brazil",

"BodyText": "...",

"Media: "..."

}

]

if(typeof require !== 'undefined') {

console.log('hey');

XLSX = require('xlsx');

}

var workbook = XLSX.readFile('./assets/visa.xlsx');

var sheet_name_list = workbook.SheetNames;

sheet_name_list.forEach(function(y) { /* iterate through sheets */

var worksheet = workbook.Sheets[y];

for (z in worksheet) {

/* all keys that do not begin with "!" correspond to cell addresses */

if(z[0] === '!') continue;

// console.log(y + "!" + z + "=" + JSON.stringify(worksheet[z].v));

}

});

XLSX.writeFile(workbook, 'out.xlsx');

回答:

改进版的“ Josh Marinacci”答案,它将超出Z列(即AA1)。

var XLSX = require('xlsx');

var workbook = XLSX.readFile('test.xlsx');

var sheet_name_list = workbook.SheetNames;

sheet_name_list.forEach(function(y) {

var worksheet = workbook.Sheets[y];

var headers = {};

var data = [];

for(z in worksheet) {

if(z[0] === '!') continue;

//parse out the column, row, and value

var tt = 0;

for (var i = 0; i < z.length; i++) {

if (!isNaN(z[i])) {

tt = i;

break;

}

};

var col = z.substring(0,tt);

var row = parseInt(z.substring(tt));

var value = worksheet[z].v;

//store header names

if(row == 1 && value) {

headers[col] = value;

continue;

}

if(!data[row]) data[row]={};

data[row][headers[col]] = value;

}

//drop those first two rows which are empty

data.shift();

data.shift();

console.log(data);

});

以上是 使用Node解析XLSX并创建json 的全部内容, 来源链接: utcz.com/qa/403926.html

回到顶部