Excel合并单元格导入HTML表格:Trainer列仅首行有值问题排查
解决Excel合并单元格解析后仅首行含Trainer字段的问题
问题原因
Excel中的合并单元格,底层仅在合并区域的首行单元格存储值,其余合并行的单元格为空。XLSX库默认读取时遵循这个存储逻辑,导致解析后的JSON数组里只有首行带Trainer字段,其余行缺失该字段。
解决方案:手动补全Trainer字段
直接遍历解析后的数组,提取首行的Trainer值,给所有缺失该字段的行补上即可。修改后的核心代码如下:
excelBinary.SheetNames.forEach(function (sheetName) { var XL_row_object = XLSX.utils.sheet_to_row_object_array(excelBinary.Sheets[sheetName]); // 获取首行的讲师值(确保首行存在Trainer字段) const trainerValue = XL_row_object[0]?.Trainer; // 遍历所有行,补全Trainer字段 const excelData = XL_row_object.map(row => { if (!row.hasOwnProperty('Trainer') && trainerValue !== undefined) { return {...row, Trainer: trainerValue}; } return row; }); console.log(excelData); })
完整修改后的代码
const Importssss = document.getElementById('importInput'); var JSONExcel = function () { this.parseExcel = function (file) { var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; var excelBinary = XLSX.read(data, { type: 'binary' }); excelBinary.SheetNames.forEach(function (sheetName) { var XL_row_object = XLSX.utils.sheet_to_row_object_array(excelBinary.Sheets[sheetName]); const trainerValue = XL_row_object[0]?.Trainer; const excelData = XL_row_object.map(row => { if (!row.hasOwnProperty('Trainer') && trainerValue !== undefined) { return {...row, Trainer: trainerValue}; } return row; }); console.log(excelData); }) }; reader.onerror = function (ex) { console.log(ex); }; reader.readAsBinaryString(file); }; }; Importssss.addEventListener('change', function (evt) { var files = evt.target.files; if (files.length !== 0) { var JSONConvert = new JSONExcel(); JSONConvert.parseExcel(files[0]); } })
这个方法简单直接,无需依赖库的特殊配置,适配绝大多数XLSX库版本。
内容的提问来源于stack exchange,提问作者Strywyr
相关产品推荐
相关产品推荐

