MFC操作Excel(Office2010)

1. 在StdAfx.h中添加#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")   //导入ADO库
2. 查看-建立类向导-Automation-Add Class – From a type library-查找出EXCEL.EXE文件(Office2010中位置:C:\Program Files\Microsoft Office\Office14中查看所有文件),依次添加_Application、Workbooks、_Workbook、Worksheets、_Worksheet、Range、Interior类
3. 在需要调用Excel报表的.cpp文件中#include "comdef.h" 和#include "excel.h"
4. 代码:
/*启动Excel服务*/
	_Application     ExcelApp;
	_Workbook        wbBook;
	_Worksheet       wsSheet;
	Range            mgXls;
	Workbooks        wbsBooks;
	Worksheets       wssSheets;
	CString          conn,find,e_message;
	Interior         it;

	HRESULT ht;
        ht = ::CoInitialize(NULL);
	if(ht == E_INVALIDARG)
	{
		AfxMessageBox("初始化COM失败", MB_ICONWARNING|MB_ICONERROR|MB_OK, 0);
	}
	if(!ExcelApp.CreateDispatch(_T("Excel.Application"),NULL))
	{
		AfxMessageBox("创建excel服务失败", MB_ICONWARNING|MB_ICONERROR|MB_OK, 0);
		::CoUninitialize();
		return FALSE;
	}

	char Excelpath[100] = {0};
	GetCurrentDirectory(sizeof(Excelpath), Excelpath);
	strcat(Excelpath,"\\XYJ-57\\Report.xlsx");

	wbsBooks.AttachDispatch(ExcelApp.GetWorkbooks(),TRUE) ;
	wbBook.AttachDispatch(wbsBooks.Add((_variant_t)Excelpath),TRUE) ;
	wssSheets = wbBook.GetWorksheets();
	wsSheet = wssSheets.GetItem(_variant_t("Sheet1"));
	wsSheet.SetName("测试报表");
	mgXls = wsSheet.GetCells();
	mgXls.AttachDispatch(wsSheet.GetCells(),TRUE) ;   //加载所有单元格
			
	mgXls.SetItem(_variant_t((long)25),_variant_t((long)5),ReadTestTime);//25:行,5列

	ExcelApp.SetVisible(TRUE) ;   //显示excel表
	mgXls.ReleaseDispatch() ;        //释放excel
	wsSheet.ReleaseDispatch() ;
	wssSheets.ReleaseDispatch() ;
	wbBook.ReleaseDispatch() ;
	wssSheets.ReleaseDispatch() ;
	ExcelApp.ReleaseDispatch() ;
	ExcelApp.Quit() ;
问题:
1) Excel操作在Debug模式下不能正常运行,但是在Realease模式下能够正常运行:
解决方法:在app的InitInstance()中添加”AfxOleInit()”,初始化组件库

你可能感兴趣的:(MFC)