2.按CTRL+W调出MFC ClassWizard,Add Class->From a type library,选择你的word的类型库(例如我的是word2003,安装在e盘,我的路径是"e:\edittools\microsoft office\office11\msword.olb"),选择完毕后,在弹出的窗口中选择要让classwizard生成的包装类,在本例中要用到_Application,Documents,_Document,Range这四个类,选中他们后按OK
3.进入你的main函数所在的cpp文件,加入头文件引用
#include "msword.h" //引用刚才classwizard生成的idispatch包装类
4.加入代码
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
{
if (CoInitialize(NULL) != S_OK)
{
AfxMessageBox("初始化COM支持库失败!");
return -1;
}
_Application wordApp;
Documents docs;
_Document doc;
Range aRange;
COleVariant vTrue((short)TRUE),
vFalse((short)FALSE),
vOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
wordApp.CreateDispatch("Word.Application",NULL);
wordApp.SetVisible(FALSE);
docs=wordApp.GetDocuments();
doc=docs.Open(COleVariant("d:\\txt.doc"),vFalse,vTrue,vFalse,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt);
aRange=doc.Range(vOpt,vOpt);
AfxMessageBox(aRange.GetText());//这里GetText得到的就是word文件的纯文本了,你可以将其写到txt文件中
doc.Close(vOpt,vOpt,vOpt);
wordApp.Quit(vOpt,vOpt,vOpt);
CoUninitialize();
}
return nRetCode;
}
{
int nRetCode = 0;
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
if (CoInitialize(NULL) != S_OK)
{
AfxMessageBox("初始化COM支持库失败!");
return -1;
}
_Application wordApp;
Documents docs;
_Document doc;
Range aRange;
COleVariant vTrue((short)TRUE),
vFalse((short)FALSE),
vOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
wordApp.CreateDispatch("Word.Application",NULL);
wordApp.SetVisible(FALSE);
docs=wordApp.GetDocuments();
doc=docs.Open(COleVariant("d:\\txt.doc"),vFalse,vTrue,vFalse,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt);
aRange=doc.Range(vOpt,vOpt);
AfxMessageBox(aRange.GetText());//这里GetText得到的就是word文件的纯文本了,你可以将其写到txt文件中
doc.Close(vOpt,vOpt,vOpt);
wordApp.Quit(vOpt,vOpt,vOpt);
CoUninitialize();
}
return nRetCode;
}