在Node中使用XLSX包上传读取Excel并替换自定义对象键
替换Excel提取数据的键以匹配MongoDB Model属性
你可以通过创建键映射表的方式,将Excel列标题(原对象键)替换为自定义的MongoDB Model属性键,具体实现步骤如下:
1. 定义键映射关系
先创建一个映射对象,把Excel里的原始列标题和你需要的Model属性一一对应,这样不管Excel列顺序如何,都能准确匹配:
// 键映射表:原始Excel列标题 => 自定义Model属性键 const keyMap = { 'Sr.\r\nNo.': 'serialNumber', 'Name and address': 'address', PAN: 'panNumber', 'Authorised Person (AP) code': 'apCode', 'Date of Approval': 'approvalDate', 'Date of withdrawal of approval': 'withdrawalDate', 'Name of the Member through which AP was registered': 'memberName', 'Name of Directors / Shareholders': 'directors' };
2. 转换数据键并处理特殊字段
遍历提取到的Excel数据,逐个对象替换键,同时注意处理Excel日期(数字格式转JS Date):
修改你的控制器代码如下:
const currDirName = __dirname; const basePath = currDirName.slice(0, currDirName.length - 11); // 移除controllers路径 const filePath = basePath + 'assets/uploadedFiles/' + req.savedFileName; const file = xlsx.readFile(filePath); const temp = xlsx.utils.sheet_to_json(file.Sheets[file.SheetNames[0]]); // 转换数据 const fileData = temp.map(item => { const transformedItem = {}; // 遍历原始对象的键值对 Object.entries(item).forEach(([originalKey, value]) => { // 匹配自定义键 const customKey = keyMap[originalKey]; if (customKey) { // 处理Excel日期:Excel日期是从1900年开始的天数,需要转换 if (customKey === 'approvalDate' || customKey === 'withdrawalDate') { transformedItem[customKey] = new Date(1900, 0, value - 1); // 修正Excel日期偏移 } else { transformedItem[customKey] = value; } } }); return transformedItem; }); console.log('转换后的数据: ', fileData);
3. 验证结果
转换后的fileData数组里的对象,键会变成你定义的serialNumber、address等,完全匹配MongoDB Model的属性,直接用于创建文档即可:
// 示例:保存到MongoDB(假设你有对应的Model,比如AuthorisedPerson) const AuthorisedPerson = require('../models/AuthorisedPerson'); AuthorisedPerson.insertMany(fileData) .then(() => console.log('数据保存成功')) .catch(err => console.error('保存失败:', err));
注意事项
- 如果Excel列标题有空格、换行符(比如
Sr.\r\nNo.),映射表的键必须完全匹配原始字符串,包括特殊字符和换行。 - Excel日期默认是数字格式,需要通过
new Date(1900, 0, value - 1)修正偏移(因为Excel把1900年当成闰年,实际不是,所以要减1)。
内容的提问来源于stack exchange,提问作者hemant
相关产品推荐
相关产品推荐

