使用read-excel-file.min.js读取Excel时如何保留原始数据格式?
解决read-excel-file读取Excel时百分比、日期格式失真问题
针对百分比格式(如7%显示为0.07)
Excel里的百分比本质是数值(0.07)+单元格格式,read-excel-file会读取原始数值,所以需要手动转换为百分比字符串:
- 读取到数值后,乘以100并加上百分号,可按需保留小数位数:
// 百分比格式化函数 function formatPercentage(value) { if (typeof value === 'number') { return `${(value * 100).toFixed(0)}%`; // 无小数位,需保留两位则改toFixed(2) } return value; // 非数值类型直接返回 }
针对日期格式(如11/08/2022显示为完整Date对象)
read-excel-file会把Excel日期转成JS Date对象,需要按指定格式(MM/DD/YYYY)格式化:
- 手动提取年、月、日拼接即可:
// 日期格式化函数 function formatDate(date) { if (date instanceof Date) { const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const year = date.getFullYear(); return `${month}/${day}/${year}`; } return date; // 非Date类型直接返回 }
结合现有代码实现修改
在生成表格行的环节,对对应列应用格式化函数。比如假设百分比在第3列、日期在第4列(索引从0开始):
// 修改原代码中生成表格行的逻辑 rows.forEach(row => { const tr = document.createElement('tr'); row.forEach((cell, index) => { const td = document.createElement('td'); // 按列索引判断并格式化 if (index === 2) { td.textContent = formatPercentage(cell); } else if (index === 3) { td.textContent = formatDate(cell); } else { td.textContent = cell; } tr.appendChild(td); }); table.appendChild(tr); });
更优雅的方式:用schema预定义解析规则
read-excel-file支持通过schema参数预先定义列的解析规则,读取时直接完成格式化:
const schema = { // 替换为你Excel中的实际列名,大小写敏感 "百分比列": { type: Number, format: value => `${(value * 100).toFixed(0)}%` }, "日期列": { type: Date, format: date => { const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const year = date.getFullYear(); return `${month}/${day}/${year}`; } } }; // 读取时传入schema readExcelFile(file, { schema }).then(({ rows }) => { // 此时rows中对应列已为格式化后的字符串,直接渲染即可 renderTable(rows); });
如果Excel无表头,可改用列索引定义schema(如0: { type: Number, format: ... })。
内容的提问来源于stack exchange,提问作者ROB
相关产品推荐
相关产品推荐

