当我们在程序中想把结果集使用EXCEL进行保存的时候,即会遇到如何使用VC写EXCEL的问题.
下面是实现的部分代码:
void CMyExcelUtil::CreateExcelFile(CString fileName)
{
try
{
COleVariant covTrue((short)TRUE);
COleVariant covFalse((short)FALSE);
COleVariant covOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR);
COleVariant m_covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
if(!excelApplication.CreateDispatch("Excel.Application"))
{
AfxMessageBox("Couldn't CreateDispatch() for Excel");
return;
}
excelApplication.SetVisible(TRUE);
lpDisp = excelApplication.GetWorkbooks(); // Get an IDispatch pointer.
ASSERT(lpDisp);
excelBooks.AttachDispatch(lpDisp); // Attach the IDispatch pointer
// to the books object.
// Open a new workbook and attach that IDispatch pointer to the
// Workbook object.
lpDisp = excelBooks.Add( covOptional );
ASSERT(lpDisp);
excelBook.AttachDispatch( lpDisp );
CString m_log;
m_log.Format("正在打开%s文件",fileName);
//AfxMessageBox(m_log);
lpDisp = excelBook.GetSheets();
ASSERT(lpDisp);
excelSheets.AttachDispatch(lpDisp);
lpDisp = excelSheets.GetItem( COleVariant((short)(1)) );
//GetItem(const VARIANT &index)
ASSERT(lpDisp);
excelSheet.AttachDispatch(lpDisp);
lpDisp = excelSheet.GetRange(COleVariant("A1"), COleVariant("A1"));
ASSERT(lpDisp);
excelRange.AttachDispatch(lpDisp);
excelRange.SetValue2(COleVariant("HelloWorld"));
lpDisp = excelSheet.GetRange(COleVariant("A2"), COleVariant("A2"));
ASSERT(lpDisp);
excelRange.AttachDispatch(lpDisp);
excelRange.SetValue2(COleVariant("88888"));
excelBook.SaveAs(COleVariant("C://readme.xls"),covOptional,covOptional,
covOptional,covOptional,covOptional,0,
covOptional,covOptional,covOptional,covOptional,covOptional);
}
catch(CException e)
{
::MessageBox(NULL, "General Exception caught.", "Catch-All",
MB_SETFOREGROUND | MB_OK);
}
}
EXCEL版本之间的兼容性非常差,百思不解!因为同是一个厂家的东西,竟然如此,难道微软的人才也流动性很大,搞的上面人的工作,后续的人理解的不透彻,只能另开发?还是微软把创新放到第一,兼容不重要,反正用户可以升级产品;否则微软如何获取MONEY.
累了,自己玩笑下:)