C++ 保存Excel文件(带密码保护)
最近有客户需求报表保存为xls的功能,需要保存的文件设置密码保护,特进行尝试!
Workbook.SaveAs method (Excel)
参数详情:https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas
C++ Code
1
2 3 4 5 6 |
void SaveAs(VARIANT &Filename, VARIANT &FileFormat, VARIANT &Password, VARIANT &WriteResPassword, VARIANT &ReadOnlyRecommended, VARIANT &CreateBackup, long AccessMode, VARIANT &ConflictResolution, VARIANT &AddToMru, VARIANT &TextCodepage, VARIANT &TextVisualLayout, VARIANT &Local)
{ static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x785, DISPATCH_METHOD, VT_EMPTY, NULL, parms, &Filename, &FileFormat, &Password, &WriteResPassword, &ReadOnlyRecommended, &CreateBackup, AccessMode, &ConflictResolution, &AddToMru, &TextCodepage, &TextVisualLayout, &Local); } |
调用实例:
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 |
BOOL bReadOnlyRecommended = TRUE;
BOOL bCreateBackup = TRUE; BOOL bLocal = TRUE; CString strXlsPath = _T("C:\\test.xls"); m_book.SaveAs( _variant_t(strXlsPath), // Filename _variant_t(-4143)/*xlWorkbookNormal*/, // FileFormat _variant_t(_T("123")), // Password _variant_t(_T("123")), // WriteResPassword _variant_t(bReadOnlyRecommended), // ReadOnlyRecommended _variant_t(bCreateBackup), // CreateBackup _variant_t(2)/*xlShared*/, // AccessMode _variant_t(2)/*xlLocalSessionChanges*/, // ConflictResolution vtMissing, vtMissing, vtMissing, _variant_t(bLocal)); // Local |
最终成功打开:
希望大家能把自己的所学和他人一起分享,不要去鄙视别人索取时的贪婪,因为最应该被鄙视的是不肯分享时的吝啬。