主题:vc读取excel出错!
代码段如下:
/////////////////////////////////////////////////////
CApplication ExcelApp; // 定义Excel应用程序
CWorkbooks wbsBooks;
CWorkbook wbBook;
CWorksheets wssSheets;
CWorksheet wsSheet;
CRange range;
LPDISPATCH lpDisp;
COleVariant vResult;
COleVariant covTrue((short)TRUE),covFalse((short)FALSE),covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
if (::CoInitialize( NULL ) == E_INVALIDARG)
{
AfxMessageBox(_T("初始化Com失败!"));
}
if ( !ExcelApp.CreateDispatch(_T("Excel.Application"), NULL))
{
AfxMessageBox(_T("创建Excel2003服务失败!"));
::CoUninitialize();
}
ExcelApp.put_Visible(TRUE);
ExcelApp.put_UserControl(TRUE);
///////////////////////////////////////// A段代码
wbsBooks.AttachDispatch(ExcelApp.get_Workbooks());
lpDisp = wbsBooks._Open("G:\\\\1.xls",
covOptional, covOptional, covOptional, covOptional, covOptional,
covOptional, covOptional, covOptional, covOptional, covOptional,
covOptional, covOptional );
wbBook.AttachDispatch(lpDisp);
wssSheets = wbBook.get_Worksheets();
wsSheet = wssSheets.get_Item(COleVariant("data")); // Get Sheet1*/
/////////////////////////////////////////// A段代码
//////////////////////////////////B段代码
lpDisp=ExcelApp.get_ActiveWorkbook();
wbBook.AttachDispatch(lpDisp);
wsSheet.AttachDispatch(wbBook.get_ActiveSheet());
/////////////////////////////B段代码
range.AttachDispatch(wsSheet.get_Cells());
range.AttachDispatch(range.get_Item(COleVariant((long)2),COleVariant((long)3)).pdispVal);
以下省略,执行A段代码可以读出数据。换成B段代码,打开G:\\\\1.xls,执行出错,调试B段代码时lpDisp没有得到赋值,不知道什么原因,谢谢!
/////////////////////////////////////////////////////
CApplication ExcelApp; // 定义Excel应用程序
CWorkbooks wbsBooks;
CWorkbook wbBook;
CWorksheets wssSheets;
CWorksheet wsSheet;
CRange range;
LPDISPATCH lpDisp;
COleVariant vResult;
COleVariant covTrue((short)TRUE),covFalse((short)FALSE),covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
if (::CoInitialize( NULL ) == E_INVALIDARG)
{
AfxMessageBox(_T("初始化Com失败!"));
}
if ( !ExcelApp.CreateDispatch(_T("Excel.Application"), NULL))
{
AfxMessageBox(_T("创建Excel2003服务失败!"));
::CoUninitialize();
}
ExcelApp.put_Visible(TRUE);
ExcelApp.put_UserControl(TRUE);
///////////////////////////////////////// A段代码
wbsBooks.AttachDispatch(ExcelApp.get_Workbooks());
lpDisp = wbsBooks._Open("G:\\\\1.xls",
covOptional, covOptional, covOptional, covOptional, covOptional,
covOptional, covOptional, covOptional, covOptional, covOptional,
covOptional, covOptional );
wbBook.AttachDispatch(lpDisp);
wssSheets = wbBook.get_Worksheets();
wsSheet = wssSheets.get_Item(COleVariant("data")); // Get Sheet1*/
/////////////////////////////////////////// A段代码
//////////////////////////////////B段代码
lpDisp=ExcelApp.get_ActiveWorkbook();
wbBook.AttachDispatch(lpDisp);
wsSheet.AttachDispatch(wbBook.get_ActiveSheet());
/////////////////////////////B段代码
range.AttachDispatch(wsSheet.get_Cells());
range.AttachDispatch(range.get_Item(COleVariant((long)2),COleVariant((long)3)).pdispVal);
以下省略,执行A段代码可以读出数据。换成B段代码,打开G:\\\\1.xls,执行出错,调试B段代码时lpDisp没有得到赋值,不知道什么原因,谢谢!