关于解析Excel中的日期出现是数字序列的问题

使用xlsx.js读取Excel中的日期有两种方式:

  1. XLSX.read(file, { type: 'binary' })

  2. XLSX.read(file, { type: 'binary', cellDates: true })

第一种方式得到的是一个 1900-01-01 00:00:00 开始的序列号。

复制代码
export function formatExcelDate(excelSerialDate) {
  //  25569 是 1970-01-01 对应的 Excel 序列号, Excel 时间起点:1900-01-01 00:00:00 , JS 时间起点:1970-01-01 00:00:00
  // 86400 * 1000 = 一天的毫秒数
  // console.log(new Date(Math.round((excelSerialDate - 25569) * 86400 * 1000)))
  return new Date(Math.round((excelSerialDate - 25569) * 86400 * 1000));
}

1. 为什么需要 excelSerialDate - 25569

excelSerialDate - 25569 目的是得到1970年1月1日至被计算的日期(excelSerialDate)相差了多少天。

2. 25569 表示1900-01-01 到 1970-01-01 有多少天,如何计算的

70年 × 365天 = 25550 天

加上闰年(1904,1908,...,1968)共 17 天

加上 Excel 闰年 bug(1900被误认为闰年)1 天

加上第1天从1开始而不是0的偏移 1 天

总计:25550 + 17 + 1 + 1 = 25569 天

3. Math.round 的作用

由于JS 使用 IEE 754 双精度浮点数表示数字,有些乘法会产生不准确的结果。

例如: 0.1 + 0.2 = 0.30000000000000004

为了解决精度问题,所以使用 Math.round 四舍五入。

4. 为什么需要转成 JS Date

JS Date 使用毫秒时间戳,所以使用 excelSerialDate - 25569 计算出从 JS 时间起点(1970-01-01)到目标日期的天数,然后乘以一天的毫秒数就得到了 JS 时间戳。

测试

复制代码
// 使用示例
const excelDate = 46170;
const jsDate = excelDateToJSDate(excelDate);
console.log(jsDate); // 2026-05-28T00:00:00.000Z

第二种方式得到是一个Date类型的数据

相关推荐
reasonsummer1 天前
【办公类-53-12】20261016(预测)Python模仿制作2026学年第二学期校历(excel+pdf,上下学期都包含)
pdf·excel
泡海椒1 天前
JQuick-Excel 自定义 SPI Provider:用 fullName 扩展 TRANSFORM 函数
驱动开发·excel
泡海椒2 天前
从 XML 到 Excel:JQuick-Excel 代理与解析器如何协作
xml·excel
优选资讯2 天前
Excel 批量打印标签的完整流程
excel
雪宫街道2 天前
SpringBoot - POI实现Excel 导入与导出
spring boot·后端·excel
Data-Miner3 天前
数据分析,除了Excel数据透视表,还有什么工具?——2026 专业精选推荐榜
microsoft·数据分析·excel
SunnyDays10113 天前
使用 Java 高效管理 Excel 批注:添加、读取、修改和删除
java·开发语言·excel
福兮说3 天前
AI 把工号整理成 Excel 后,前面的 0 还在吗?我会先核对这三列
excel
工具派4 天前
JSON转Excel后18位订单号不对了?数字精度与类型边界实测
json·excel