在Node中使用XLSX包上传n读取带有自定义对象键的Excel文件

问题描述 投票:0回答:1

需要上传 Excel 文件以将数据存储在 Node/Mogo 应用程序中。 我能够上传文件并提取数据。 数据采用对象数组的形式,每个对象都有键作为 Excel 文件的列标题。 我需要使用自己的对象键来替换从列标题生成的键。 这是为了映射保存此数据的模型的属性。 假设我知道列的顺序,我该如何实现这一点。

节点控制器:

    const currDirName = __dirname;
    const basePath = currDirName.slice(0, currDirName.length - 11); // removing controllers from path
    const filePath = basePath + 'assets/uploadedFiles/' + req.savedFileName
    const file = xlsx.readFile(filePath);
    let fileData = [];
    const temp = xlsx.utils.sheet_to_json(file.Sheets[file.SheetNames[0]])
    temp.forEach(res => fileData.push(res))
  
    console.log('uploaded file data: ', fileData);

控制台输出

[{
    'Sr.\r\nNo.': 1,
    'Name and address': 'Shop No. 3, ABC Arcade,\r\n' +     
      'Opp. PKA, XYZ Lane,\r\n' +
      'J.P. Road, Andheri (West), Mumbai - 400068. Maharashtra',
    PAN: 'AAAPA1234B',
    'Authorised Person (AP) code': 'MCX/AP/6337',
    'Date of Approval': 40570,
    'Date of withdrawal of approval': 41508,
    'Name of the Member through which AP was registered': 'ABC Commodity Services Pvt. Ltd.',        
    'Name of Directors / Shareholders': 'N.A.'
},....
]

需要有我自己的上述对象的密钥。

node.js xlsx
1个回答
0
投票

在阅读工作表时,您可以通过提供

headers
选项来添加自定义标题,该选项包含将用作标题的键数组,即对象属性。 另外,使用
.slice(1)
跳过带有标题的第一行。

试试这个:

const currDirName = __dirname;
const basePath = currDirName.slice(0, currDirName.length - 11); // removing controllers from path
const filePath = basePath + 'assets/uploadedFiles/' + req.savedFileName
const file = xlsx.readFile(filePath);

// add your headers array here
const opts = {
    header: ['heading1', 'heading2..etc']
};

const file = xlsx.readFile(filePath);
// slice to skip heading row
let fileData = xlsx.utils.sheet_to_json(file.Sheets[file.SheetNames[0]], opts).slice(1);

console.log('uploaded file data: ', fileData);
© www.soinside.com 2019 - 2024. All rights reserved.