本文共 1510 字,大约阅读时间需要 5 分钟。
首先,需要通过 npm 安装 node-xlsx 库:
npm install node-xlsx --save-dev
使用 node-xlsx 库读取 Excel 文件,可以按照以下步骤操作:
const xlsx = require('node-xlsx');const sheets = xlsx.parse('F:\\123.xlsx'); 注意:确保文件路径正确,建议使用绝对路径。
读取完成后,sheets 会是一个数组,包含所有工作表。具体内容可以通过遍历 sheets 来查看。
Excel 中的日期格式在 Node.js 中可能会以特定方式存储,下面提供一个将日期格式转换为 Date 对象的方法:
const getFormatDate_XLSX = (serial: number) => { const utc_days = Math.floor(serial - 25569); const utc_value = utc_days * 86400; const date_info = new Date(utc_value * 1000); const fractional_day = serial - Math.floor(serial) + 0.0000001; const total_seconds = Math.floor(86400 * fractional_day); const seconds = total_seconds % 60; const total_seconds -= seconds; const hours = Math.floor(total_seconds / (60 * 60)); const minutes = Math.floor(total_seconds / 60) % 60; const d = new Date( date_info.getFullYear(), date_info.getMonth(), date_info.getDate(), hours, minutes, seconds ); const add0 = (m: number) => m < 10 ? '0' + m : m.toString(); return `${add0(d.getFullYear())}-${add0(d.getMonth() + 1)}-${add0(d.getDate())} ${add0(d.getHours())}:${add0(d.getMinutes())}:${add0(d.getSeconds())}`;}; 完整的使用示例代码如下:
const xlsx = require('node-xlsx');const sheets = xlsx.parse('F:\\123.xlsx');console.log('内容:', sheets); 通过以上方法,可以轻松读取并处理 XLSX 文件内容。希望以上内容对您有所帮助!
转载地址:http://ftjfk.baihongyu.com/