简体   繁体   English

如何从 Excel 中读取 A 列中的数据

[英]How To Read Data From Column A From Excel

I'm trying to get the data from a given column from excel in nodejs (for example, column "Emails"), work with the data and then export the result in the same excel, in a new column named "Emails-Result".我正在尝试从 nodejs 中的 excel 给定列中获取数据(例如,列“电子邮件”),处理数据,然后将结果导出到同一个 excel 中名为“电子邮件结果”的新列中.

This is what I tried by fetching the data:这是我通过获取数据尝试的:

const xlsx = require('xlsx');


const emails = [];
                        var workbook = xlsx.readFile(`./view/assets/uploads/${filename}`);
                        var first_sheet_name = workbook.SheetNames[0];
                        var address_of_cell = 'Emails';
                        var worksheet = workbook.Sheets[first_sheet_name];
                        var desired_cell = worksheet[address_of_cell];
                        emails.push(desired_cell.v);

                        console.log(emails);

but I get this error:但我收到此错误:

TypeError: Cannot read property 'v' of undefined

so the data couldn't be retrieved.所以无法检索数据。

Also, how can I make a new column (if not exists) and add the result in it?另外,如何创建一个新列(如果不存在)并将结果添加到其中?

Any ideas, please?有什么想法吗?

You cannot just pass the string and expect that you'll get that column, you have to find the name of the cells which you will accrue.您不能只传递字符串并期望获得该列,您必须找到将产生的单元格的名称。

const columnName = Object.keys(worksheet).find(key=> worksheet[key].v === address_of_cell);

Finding the name is done by passing the 'Emails' and searching which cell names are to be parsed.查找名称是通过传递“电子邮件”并搜索要解析的单元格名称来完成的。

This will work:这将起作用:

const xlsx = require('xlsx');


const emails = [];
var workbook = xlsx.readFile(`./view/assets/uploads/${filename}`);
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = 'Emails';
var worksheet = workbook.Sheets[first_sheet_name];
const columnName = Object.keys(worksheet).find(key=> worksheet[key].v === address_of_cell);

for (let key in worksheet) {
  if (key.toString()[0] === columnName[0]) {
    emails.push(worksheet[key].v);
  }
}
console.log('Result list', emails)

Likewise, instead of the for in loop you could stay functional and avoid array declaration and worksheet object reference同样,代替 for in 循环,您可以保持功能并避免数组声明和工作表对象引用

const emails = Object.entries(worksheet)
  .filter(([key, value]) => key.toString()[0] === columnName[0])
  .map(([key, value]) => value.v)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM