VC Excel operation in OLE

本文详细介绍了如何在Visual C++环境中通过Excel服务器操作Excel文件,包括设置工作簿可见性、引入类库、打开保护文件、读取工作表内容等关键步骤。提供了具体的代码示例,并讨论了遇到密码保护文件时的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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栏格中数字。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值