gpt4 book ai didi

JavaScript (node js) 在读取 Excel 文件时跳过空单元格

转载 作者:行者123 更新时间:2023-11-30 15:07:21 28 4
gpt4 key购买 nike

我正在做一个小任务,读取 Excel 工作表并以 json 格式保存。当所有单元格值都存在时,我使用的代码运行良好,如果有任何空单元格,它会跳过该单元格。

如果未显示任何值(在我的情况下我错过了 cust2 电话号码),我想要的输出如下所示。

[ { cust_name: 'Ben',
cust_city: '街道1',
cust_country: 'country1',
phno: 1 },
{ cust_name: '肯',
cust_city: 'street2',
cust_country: 'country2'
phno:},
{ cust_name: '罗恩',
cust_city: 'street3',
cust_country: 'country3',
phno: 3 } ]

但是我得到的输出是

[ { cust_name: 'Ben',
cust_city: '街道1',
cust_country: 'country1',
phno: 1 },
{ cust_name: '肯',
cust_city: 'street2',
cust_country: 'country2' },
{ cust_name: '罗恩',
cust_city: 'street3',
cust_country: 'country3',
phno: 3 } ]

它错过了为 cust2 提交的 phno

请帮助我弄清楚我必须在我的代码中更改什么才能获得我想要的输出。

我的代码是

 var XLSX = require('xlsx');
var workbook = XLSX.readFile('customer.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 col = z.substring(0,1);
var row = parseInt(z.substring(1));
var value = worksheet[z].v;

//store header names
if(row == 1) {
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);
});

提前致谢!

最佳答案

我遇到了同样的问题,在阅读了库文档后,上述问题的解决方案是将可选参数传递给 XLSX.readFile 函数。

即改变

来自:var workbook = XLSX.readFile('customer.xlsx');

到: var workbook = XLSX.readFile('customer.xlsx', {sheetStubs: true});

可选对象中的 sheetStubs 参数允许库列出默认情况下被库的数据处理实用程序忽略的单元格。

** 浏览图书馆的以下部分 documentation

1)解析选项2)数据类型(强调数据类型z)。

关于JavaScript (node js) 在读取 Excel 文件时跳过空单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45545863/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com