(1)在afxstd.h文件中包含头文件如下:
#include <atlbase.h> extern CComModule _Module; #include <atlcom.h>
(2)在程序APP文件中,声明如下:
CComModule _Module;//全局变量 BOOL CMFCApplication1App::InitInstance() {//初始化报表COM组件 HRESULT hRes = ::CoInitialize(NULL); ATLASSERT(SUCCEEDED(hRes)); _Module.Init(0, AfxGetInstanceHandle()); //...... } int CMFCApplication1App::ExitInstance() {//重写虚函数 _Module.Term(); ::CoUninitialize(); return CWinApp::ExitInstance(); }
(3)在对话框的头文件中,加入如下:
#include "GetPath.h" #include "GRImport.h"
当然需要先将Grid++report目录下的Utility文件夹复制到工程目录中,并在“项目属性->VC++目录->包含目录”添加Utility文件夹。
(4)在对话框类中添加成员变量:IGridppReportPtr m_pGridppReport;
BOOL CMFCApplication1Dlg::OnInitDialog() { //创建报表主对象 m_pGridppReport.CreateInstance(__uuidof(GridppReport)); ATLASSERT(m_pGridppReport != NULL); //加载模板文件 //从文件中载入报表模板数据到报表主对象 CString FileName = GetReportTemplatePath(_T("标准过磅单1.grf")); m_pGridppReport->LoadFromFile((LPCTSTR)FileName); //第(7)步还有代码 }
void CMFCApplication1Dlg::OnDestroy() { CDialogEx::OnDestroy(); //释放主报表对象 m_pGridppReport.Release(); } void CMFCApplication1Dlg::OnBnClickedButton1() { //直接打印报表 m_pGridppReport->Print(TRUE); } void CMFCApplication1Dlg::OnBnClickedButton2() { // 显示预览窗口 m_pGridppReport->Title = _T("标准过磅单1"); m_pGridppReport->PrintPreview(TRUE); }
(5)同时将导出库复制到工程路径下,即gregn.tlb 和 grdes.tlb
(6)要动态修改报表参数,可以新建一个类,继承报表事件处理接口。
//Scale3DCReportEvent.h头文件 #pragma once #include "GridppReportEventImpl.h" class CScale3DCReportEvent :public CGridppReportEventImpl { public: CScale3DCReportEvent(); ~CScale3DCReportEvent(); virtual void Initialize(void); IGridppReportPtr m_pGridppReport; };
//Scale3DCReportEvent.cpp文件 #include "stdafx.h" #include "Scale3DCReportEvent.h" #include "GridppReportEventImpl.c" CScale3DCReportEvent::CScale3DCReportEvent() { } CScale3DCReportEvent::~CScale3DCReportEvent() { } void CScale3DCReportEvent::Initialize(void) { m_pGridppReport->ParameterByName(_T("车号"))->AsString =_T("猎豹太空梭0X29"); }
(7)在相应的对话框头文件中包含:
#include "Scale3DCReportEvent.h"//事件包装类
#include "GetPath.h" //上面步骤已包含过
#include "GRImport.h"
在窗口类中声明成员变量:
//报表事件代理指针
CGridppReportEventImpl *m_pReportEvents;
在窗口的OnInitDialog()中添加如下代码:
//创建事件响应对象 CComObject<CScale3DCReportEvent> *pEvent; CComObject<CScale3DCReportEvent>::CreateInstance(&pEvent); m_pReportEvents = pEvent; m_pReportEvents->AddRef(); pEvent->m_pGridppReport = m_pGridppReport;//事件代理指针 HRESULT hr = m_pReportEvents->DispEventAdvise(m_pGridppReport, &__uuidof(_IGridppReportEvents)); ATLASSERT( SUCCEEDED(hr) );
(8)在ON_WM_DESTROY消息中继续添加代码:
//释放事件代理 if (m_pReportEvents != NULL) { HRESULT hr = m_pReportEvents->DispEventUnadvise(m_pGridppReport, &__uuidof(_IGridppReportEvents)); m_pReportEvents->Release(); m_pReportEvents = NULL; ATLASSERT(SUCCEEDED(hr)); }
原文地址:http://blog.51cto.com/9233403/2118571