用VC对Office进行操作的介绍已经不少了,但是从来没有把word,excel,powerPoint进进全面的介绍的。由于工作的需要,我需要对在自己的软件中对word,excel,powerPoint进行操作。所以把自己的体会写出来和大家分享,希望对大家有所帮助。当然还有很多不当之处,希望大家指出。
用例子来说明吧,首先创建一个MFC AppWizard(EXE)工程,然后通过在VIEW菜单中,选ClassWizard,选Automation选项卡,选Add Class,选择From a TypeLibrary, 选中Microsoft Office 2000 类型库:Excel9.olb,MSPPT9.OLB,MSWORD9.OLB(在Microsoft Office\Office目录下) 会将类型库中的所有类添加到你的工程中。
然后写一个类来操作Office吧!
ObtGuiGcomOfficePrinter.h
#if !defined(AFX_OBTGUIGCOMOFFICEPRINTER_H__03A0C2D8_DFC8_4B51_8ADB_994B86BACB82__INCLUDED_)
#define AFX_OBTGUIGCOMOFFICEPRINTER_H__03A0C2D8_DFC8_4B51_8ADB_994B86BACB82__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "comdef.h"
#include "ObtGuiGcomMsWord9.h"
#include "ObtGuiGcomMsPpt9.h"
#include "ObtGuiGcomExcel9.h"
class AFX_EXT_CLASS ObtGuiGcomOfficePrinter
{
public:
ObtGuiGcomOfficePrinter();
virtual ~ObtGuiGcomOfficePrinter();
//Operator
public:
BOOL WordPrinterToJcf(LPCTSTR lpszFileName,LPCTSTR lpszActivePrinter);
BOOL ExcelPrinterToJcf(LPCTSTR lpszFileName,LPCTSTR lpszActivePrinter);
BOOL PowerPointPrinterToJcf(LPCTSTR lpszFileName,LPCTSTR lpszActivePrinter);
};
#include "stdafx.h"
#include "ObtGuiGcomOfficePrinter.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
ObtGuiGcomOfficePrinter::ObtGuiGcomOfficePrinter()
{
}
ObtGuiGcomOfficePrinter::~ObtGuiGcomOfficePrinter()
{
}
BOOL ObtGuiGcomOfficePrinter::PowerPointPrinterToJcf(LPCTSTR lpszFileName,LPCTSTR lpszActivePrinter)
{
_PptApplication m_powerpointApp;
Presentations m_powerpointPres;
_Presentation m_powerpointPre;
m_powerpointPres.ReleaseDispatch();
m_powerpointPre.ReleaseDispatch();
if(!m_powerpointApp.CreateDispatch("PowerPoint.Application"))
{
AfxMessageBox("创建PowerPoint服务失败!");
return FALSE;
}
m_powerpointApp.m_bAutoRelease=true;
m_powerpointApp.SetVisible(TRUE);//对于PowerPoint必须设置为TRUE
m_powerpointPres.AttachDispatch(m_powerpointApp.GetPresentations());
m_powerpointPres.Open(lpszFileName,-1,-1,-1);
m_powerpointPre.AttachDispatch(m_powerpointApp.GetActivePresentation(),TRUE);
m_powerpointPre.PrintOut(-1,-1,"",long(1),-1);
m_powerpointApp.Quit();
m_powerpointPre.ReleaseDispatch();
m_powerpointPres.ReleaseDispatch();
m_powerpointApp.ReleaseDispatch();
return TRUE;
}
BOOL ObtGuiGcomOfficePrinter::ExcelPrinterToJcf(LPCTSTR lpszFileName,LPCTSTR lpszActivePrinter)
{
_ExcelApplication m_excelApp;//定义Excel提供的应用程序对象
Workbooks m_excelBooks;
_Workbook m_excelBook;
m_excelBooks.ReleaseDispatch();
m_excelBook.ReleaseDispatc