MFC对Excel表格读写访问实例,
CApplication app;
CWorkbooks books;
CWorkbook book;
CWorksheets sheets;
CWorksheet sheet;
CRange range;
CRange iCell;
LPDISPATCH lpDisp;
COleVariant vResult;
COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
if(!app.CreateDispatch(_T("Excel.Application")))
{
AfxMessageBox(_T("无法启动Excel服务器!"));
return;
}
books.AttachDispatch(app.get_Workbooks());
lpDisp = books.Open(_T("d:\\test1.xlsx"),
covOptional, covOptional, covOptional, covOptional, covOptional,
covOptional, covOptional, covOptional, covOptional, covOptional,
covOptional, covOptional, covOptional, covOptional);
//得到Workbook
book.AttachDispatch(lpDisp);
//得到Worksheets
sheets.AttachDispatch(book.get_Worksheets());
//得到当前活跃sheet
//如果有单元格正处于编辑状态中,此操作不能返回,会一直等待
//lpDisp = book.get_ActiveSheet();
lpDisp = sheets.get_Item(_variant_t(_T("Sheet1")));
sheet.AttachDispatch(lpDisp);
//读取第一个单元格的值
range.AttachDispatch(sheet.get_Cells());
iCell.AttachDispatch(range.get_Item(COleVariant((long)2), COleVariant((long)1)).pdispVal);
vResult = iCell.get_Value2();
CString str;
if (vResult.vt == VT_BSTR)
{
str = vResult.bstrVal;
}
else if (vResult.vt == VT_R8)
{
str.Format(_T("%f"), vResult.dblVal);
}
books.Close();
//释放对象
iCell.ReleaseDispatch();
range.ReleaseDispatch();
sheet.ReleaseDispatch();
sheets.ReleaseDispatch();
book.ReleaseDispatch();
books.ReleaseDispatch();
app.Quit();
app.ReleaseDispatch();