在VC中操作Excel文件需要引入Excel服务器,在VC中添加Class, 在from type library中引入Excel.exe,如下,

具体代码示例如下,
exlapp.put_Visible(FALSE); //set the excel sheet invisible to the user! otherwise the excel sheet will be opened and visible
exlapp.put_UserControl(TRUE);
//获取主程序所在路径,存在sPath中
GetModuleFileName(NULL,sPath.GetBufferSetLength(MAX_PATH+1),MAX_PATH);
sPath.ReleaseBuffer();
int nPos;
nPos=sPath.ReverseFind ('\\');
sPath=sPath.Left(nPos);
sFile = sPath + CString("\\pw.xls"); // 将被读取的Excel文件名
try{
wbks = exlapp.get_Workbooks();
wbk = wbks.Open(sFile, VOptional, VOptional, VOptional, _variant_t("username"), _variant_t("password"),
VOptional,VOptional,VOptional,VOptional,VOptional,VOptional,VOptional,VOptional,VOptional);
}
//the excel file was protected by password
catch (CException *e){
TCHAR msg[1024] = {0};
e->GetErrorMessage(msg, 1024);
e->ReportError();
e->Delete();
AfxMessageBox(msg);
if (log)
log->Error(_T("Error occurred in opening pw.xls file. Cause of %s"), msg);
}
//wbks.Open(
whts = wbk.get_Worksheets();
wht = whts.get_Item(COleVariant((short)1));
//read out the Excel sheet content
CRange range, currentRange;
VARIANT varItemName;
具体函数使用
range.get_Item( COleVariant( (long)(i + 1)), COleVariant((long)j)).pdispVal, TRUE)
读取第i+1行,j栏格中数字。
本文详细介绍了如何在Visual C++环境中通过Excel服务器操作Excel文件,包括设置工作簿可见性、引入类库、打开保护文件、读取工作表内容等关键步骤。提供了具体的代码示例,并讨论了遇到密码保护文件时的处理方式。
6250

被折叠的 条评论
为什么被折叠?



