Node.js如何读取带密码保护的Excel文件?求适用类库
处理加密Excel文件的Node.js库推荐
嘿,我刚好碰到过类似的需求!确实ExcelJS和node-xlsx本身没有内置处理加密Excel的能力,但Node.js生态里还是有几个实用的工具能帮你搞定这个问题,给你整理几个靠谱的选项:
1. xlsx-populate
这是我用过最顺手的库之一,专门支持读写带密码保护的.xlsx格式文件,API设计也比较直观。
示例代码(读取加密文件):
const XlsxPopulate = require('xlsx-populate'); // 异步读取加密Excel XlsxPopulate.fromFileAsync('your-encrypted-file.xlsx', { password: 'your-secure-password' }) .then(workbook => { // 获取第一个工作表的A1单元格值 const cellValue = workbook.sheet(0).cell('A1').value(); console.log('读取到的内容:', cellValue); // 如果你需要修改内容后保存,也可以直接调用saveAsync // return workbook.saveAsync('decrypted-and-edited.xlsx'); }) .catch(error => { console.error('处理失败:', error.message); });
注意:它只支持.xlsx格式,不兼容旧版的.xls文件。
2. 通过LibreOffice命令行调用(兼容全格式)
如果你需要处理.xls或者其他Office加密文档,这个方案会更通用——通过Node.js的child_process模块调用LibreOffice的命令行工具来解密文件,之后再用你熟悉的ExcelJS/node-xlsx读取解密后的文件。
示例代码:
const { exec } = require('child_process'); const fs = require('fs').promises; const path = require('path'); async function decryptAndReadExcel(encryptedPath, password) { const tempDir = './temp-decrypted'; await fs.mkdir(tempDir, { recursive: true }); // 构建LibreOffice解密命令(需确保系统已安装LibreOffice) const decryptCmd = `libreoffice --headless --convert-to xlsx --outdir ${tempDir} --password '${password}' ${encryptedPath}`; return new Promise((resolve, reject) => { exec(decryptCmd, async (err, stdout, stderr) => { if (err) { reject(new Error(`解密失败: ${stderr || err.message}`)); return; } // 找到解密后的文件(LibreOffice会自动生成同名xlsx) const decryptedFileName = path.basename(encryptedPath, path.extname(encryptedPath)) + '.xlsx'; const decryptedPath = path.join(tempDir, decryptedFileName); // 这里用ExcelJS读取解密后的文件 const { Workbook } = require('exceljs'); const workbook = new Workbook(); await workbook.xlsx.readFile(decryptedPath); // 读取完成后可以删除临时文件 await fs.unlink(decryptedPath); resolve(workbook); }); }); } // 调用示例 decryptAndReadExcel('old-encrypted-file.xls', 'your-password') .then(workbook => { const sheet = workbook.getWorksheet(1); console.log('第一行内容:', sheet.getRow(1).values); }) .catch(err => console.error(err));
优点:支持几乎所有Office文档格式(包括.xls、.xlsx甚至.doc等);缺点:需要系统提前安装LibreOffice,适合后端环境可控的场景。
3. 其他小众选项
xlsx-crypt:基于SheetJS的扩展库,支持解密.xlsx文件,但维护活跃度不如xlsx-populate,使用前建议查看最新issues。node-xlsx-encrypt:主要用于生成加密Excel,读取加密文件的功能相对有限,适合写入场景优先的需求。
总结一下:如果只需要处理.xlsx,优先选xlsx-populate;如果要兼容旧格式,LibreOffice命令行方案更稳妥。
内容的提问来源于stack exchange,提问作者Konstantin Fedorov




