VC2008 操作调用 Word 控件

原文地址:http://www.5xsoft.com/Article.aspx?id=239

现在在网上搜“VC操作word”的信息基本都是vc6的资料,vs2005以后的比较少了,按照老资料的步骤去做最后在编译时会报错的;

1.在VS2005中新建一控制台程序,选支持MFC

2. Project-> Add Class->MFC Class From Typelib,单选File,找到你的word的类型库(例如我的word安装路径是"D://Program Files//Microsoft Office//OFFICE11//MSWORD.OLB"),在本例中要用到_Application,Documents,_Document,Range这四个类,选中它们后按OK  
 

3.头文件中将

#import "D://Program Files//Microsoft Office//OFFICE11//MSWORD.OLB" no_namespace

换成

#import "D://Program Files//Microsoft Office//OFFICE11//MSWORD.OLB" no_namespace    raw_interfaces_only /
rename("FindText","_FindText")       /
rename("Rectangle","_Rectangle")   /
rename("ExitWindows","_ExitWindows")

 

否则,出现大量编译错误


3.读取code如下

#include "stdafx.h" #include "ReadWord.h" #include "CApplication.h" #include "CDocumentEx.h" #include "CRange.h" #include "CDocuments.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // The one and only application object CWinApp theApp; using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { cerr << _T("Fatal Error: MFC initialization failed") << endl; nRetCode = 1; } else { // 变量的声明 COleVariant vTrue((short)TRUE), vFalse((short)FALSE), vOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);// 缺省对象 CComVariant tpl(_T("D://test.doc")), NewTemplate(false), DocType(0), Visble; // BuildJob test.doc CApplication oWordApp ; CDocuments oDocs ; CDocumentEx oDoc ; CRange range ; if (CoInitialize(NULL) != S_OK) return -1; //建立一个word实例对象 if (!oWordApp.CreateDispatch(TEXT("Word.Application")) ){ AfxMessageBox( TEXT( "CreateDispatch failed." ) , MB_OK|MB_SETFOREGROUND); return -1; } oWordApp.put_Visible(FALSE); //创建文档 oDocs = oWordApp.get_Documents(); //打开一个新文档,将D://test.doc文件的内容添加到新文档中 oDoc = oDocs.Add(&tpl,&NewTemplate,&DocType,&Visble); range = oDoc.Range(vOpt,vOpt); AfxMessageBox(range.get_Text()); range.ReleaseDispatch(); oDocs.ReleaseDispatch(); oDoc.ReleaseDispatch(); oWordApp.ReleaseDispatch(); CoUninitialize(); } return nRetCode; }

注意:

1.#import后面的"/"应该保留,且“no_namespace    raw_interfaces_only /”应跟在第一行后面;

你可能感兴趣的:(application,initialization,mfc,文档,null,class)