AX2012R3:如何在X++中导入带密码保护的Excel文件
在X++中导入受密码保护的Excel文件
要导入带密码的Excel文件,只需在调用workbooks.open()方法时传入对应的密码参数即可——Excel的COM原生Workbooks.Open方法本身就支持密码参数。
修改后的代码
pathName = strFmt('%1', PathCtrl.Text()); excel = SysExcelApplication::construct(); workbooks = excel.workbooks(); try { // 调用Open方法时添加密码参数,第5个参数为打开文件的密码 workbooks.open(@pathName, false, false, '', '你的密码'); workbook = workbooks.item(1); worksheets = workbook.worksheets(); worksheet = worksheets.itemFromNum(3); cells = worksheet.cells(); type = cells.item(row+1, 1).value().variantType(); record_count = this.findLastRow(worksheet); _Progress.setTotal(record_count); while (type != COMVariantType::VT_EMPTY) { row++; info(strFmt("%1", cells.item(row,1).value().bStr())); type = cells.item(row+1, 1).value().variantType(); _Progress.setText(strFmt("%1 : %2 / %3", cells.item(row, 2).value().bStr(), row, record_count)); _Progress.setCount(row); _Progress.update(true); } excel.quit(); // 释放COM对象,避免进程残留 new InteropPermission(InteropKind::ComInterop).assert(); System::GC::Collect(); System::GC::WaitForPendingFinalizers(); CodeAccessPermission::revertAssert(); } catch (Exception::Error) { excel.quit(); // 异常时也要释放COM对象 new InteropPermission(InteropKind::ComInterop).assert(); System::GC::Collect(); System::GC::WaitForPendingFinalizers(); CodeAccessPermission::revertAssert(); throw error("File cannot be opened"); }
参数说明
Workbooks.Open方法的关键参数(按顺序):
- 文件路径(必填)
- 是否只读打开(默认false)
- 是否以独占模式打开(默认false)
- 写保护密码(如果文件仅设置打开密码,此处留空)
- 打开文件的密码(你的Excel文件密码填在这里)
注意事项
- 密码需与文件设置完全一致,包括大小写、特殊字符,否则会触发异常
- 务必在代码中释放Excel COM对象(通过GC回收),避免Excel进程在后台残留
- 该方法适用于.xls、.xlsx等所有Excel支持的加密格式
内容的提问来源于stack exchange,提问作者nuttapol madee
相关产品推荐
相关产品推荐

