使用节点js从excel读取命名的单元格/范围

时间:2019-07-23 07:21:15

标签: javascript node.js js-xlsx

我正在解析Excel文件并尝试从中获取信息。所有文件都具有相同的命名范围。我程序的目的是解析所有文件以汇总数据。 我已经尝试了包xlsx。使用该程序包,我可以从excel文件中获取数据,可以获取定义的名称,但是,我不了解如何使用定义的名称获取其值。也许另一个软件包会更有帮助?

这是下面的代码:

var XLSX = require("xlsx");
var workbook = XLSX.readFile("myWorkbook.xlsx");
var sheet_name_list = workbook.SheetNames;

let SummarySheet = sheet_name_list.findIndex(elt => {
  return elt === "Summary"; //the values I am looking for are in summary sheets
});

let worksheet = workbook.Sheets[sheet_name_list[SummarySheet]];

let datesIndex = workbook.Workbook.Names.findIndex(elt => {
  return (elt.Name === "myDate") & (elt.Sheet !== 0);
});
let myDates = workbook.Workbook.Names[datesIndex].Ref; //this gives Summary!$11:$11 

console.log(worksheet[myDates]); //this renders undefined 
console.log(worksheet['A1:B1']); //this renders undefined

console.log(worksheet['A1']); //this renders the correct value of cell A1

我希望单元格的值在Summary!$ 11:$ 11

范围内。

非常感谢您的帮助!

[编辑]我错误地删除了我的评论,但这里是: @不幸的是,@ Cat XLSX.utils.sheet_to_row_object_array(workbook.Sheets [sheetName])松开了定义的名称。

@AM我已经尝试使用convert-excel_to_json,但是在这里丢失了已定义的命名单元。

1 个答案:

答案 0 :(得分:1)

我可以使用以下代码访问Excel工作表中的命名范围,我必须解析范围ref,然后才能对其进行循环:

var XLSX = require("xlsx");
var workbook = XLSX.readFile("myWorkbook.xlsx");
var sheet_name_list = workbook.SheetNames;

let SummarySheet = sheet_name_list.findIndex(elt => {
    return elt === "Summary"; //the values I am looking for are in summary sheets
});

var worksheet = workbook.Sheets[sheet_name_list[SummarySheet]];

var datesIndex = workbook.Workbook.Names.findIndex(elt => {
    return (elt.Name === "myDate") && (elt.Sheet !== 0);
});

var myDates = workbook.Workbook.Names[datesIndex].Ref;

// Get the sheet specific range..
myDates = myDates.split('!')[1];

console.log(“ myDates”,myDates);     console.log(“ myDates:Sheetref”,myDates);

// Get the decoded range for the named range..
var range = XLSX.utils.decode_range(myDates);

// Get the range of the worksheet..
var worksheetRange = XLSX.utils.decode_range(worksheet['!ref']);

// If our named range overlaps the worksheet range set this for the columns.
if (!range.s.c || range.s.c <= 0) range.s.c = worksheetRange.s.c;
if (!range.e.c || range.e.c <= 0) range.e.c = worksheetRange.e.c;

// Loop over the referenced range..
for(var R = range.s.r; R <= range.e.r; ++R) {
    for(var C = range.s.c; C <= range.e.c; ++C) {
        var cell_address = {c:C, r:R};
        console.log(cell_address);
        console.log(worksheet[XLSX.utils.encode_cell(cell_address)]);
    }
}