js-xlsx - 获取Excel表格特定行

4

我有一个Excel表格,共有500行。我正在试图获取101到200行。

我在Google中搜索过,并找到了一个获取开始行的示例,例如1到100或1到1000,甚至是1到任何数字。

但我没有找到获取从第m行到第n行的代码(这里的'm'和'n'可以是任意数字,例如m=101到n=200)

以下是我找到的获取前100行的代码:

  let workbook = XLSX.readFile('./files/uploaded_files/testfile.xlsx', {sheetRows: 100})
  const wsname = workbook.SheetNames[0];
  const ws = workbook.Sheets[wsname];
  var exceldata = XLSX.utils.sheet_to_json(ws);

即使有其他模块可以获取中间行,我还想知道是否还有别的方法?

1个回答

4

使用较小的示例:

enter image description here

有几个选择:

您可以使用当前的方法并从 sheet_to_json 返回的数组中进行切片(slice)

// option 1
const maxRow = 6;
const minRow = 3;
const wb = XLSX.readFile("./Book1.xlsx", {sheetRows: maxRow});
const ws = wb.Sheets[wb.SheetNames[0]];
let data = XLSX.utils.sheet_to_json(ws);
data = data.slice(minRow <= 2 ? 0 : minRow - 2);
console.log(data);

这里的 minRow - 2 是为了考虑到第一行是表头,而另一个1是为了包括第3行而不是排除它。这将产生以下结果:

[  { a: 4, b: 5, c: 6 },  { a: 7, b: 8, c: 9 },  { a: 10, b: 11, c: 12 },  { a: 13, b: 14, c: 15 }]

另一个选项是结合使用 rangeheader 选项(参见这里)。range 允许您控制 sheet_to_json 考虑的范围,而 header 用于定义输出对象数组中使用的键。

您可以在导入整个文件后使用此选项,或者继续使用 sheetRows 选项,例如:

// option 2
const importRange = "A3:F6";
const headers = ["a", "b", "c"];
const wb = XLSX.readFile("./Book1.xlsx"); // not using sheetRows
const ws = wb.Sheets[wb.SheetNames[0]];
const data = XLSX.utils.sheet_to_json(ws, {range: importRange, header: headers});
console.log(data);

这将生成:

[  { a: 4, b: 5, c: 6 },  { a: 7, b: 8, c: 9 },  { a: 10, b: 11, c: 12 },  { a: 13, b: 14, c: 15 }]

请注意,如果省略headers选项,则输出结果为:

[
  { '4': 7, '5': 8, '6': 9 },
  { '4': 10, '5': 11, '6': 12 },
  { '4': 13, '5': 14, '6': 15 }
]

因为第3行的值成为新的默认标题(我认为您可能不想要这样)。

最后,如果您事先不知道标题,可以获取一个数组,并稍后确定标题:

// option 3
const importRange = "A3:F6";
const headers = 1; 
const wb = XLSX.readFile("./Book1.xlsx"); // not using sheetRows
const ws = wb.Sheets[wb.SheetNames[0]];
const data = XLSX.utils.sheet_to_json(ws, {range: importRange, header: headers});
console.log(data);

生成:

[ 
  [ 4, 5, 6 ],
  [ 7, 8, 9 ],
  [ 10, 11, 12 ],
  [ 13, 14, 15 ] 
]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接