描述:
初始化:
if(!AfxOleInit())
{
AfxMessageBox("Could not initialize COM services");
return FALSE;
}
_Application wordApp;
_Document doc;
Documents docs;
Paragraphs pgraphs;
Paragraph pgraph;
Range range;
COleVariant vFileName("c:\\a3.doc");
COleVariant varstrNull("");
COleVariant vLong((long)DISP_E_PARAMNOTFOUND,VT_ERROR);
COleVariant vTrue((short)TRUE);
COleVariant vFalse((short)FALSE);
CFile myfile;
CString strBuf;
long i;
//创建一个新的word程序
if(!wordApp.CreateDispatch("Word.Application",NULL))
{
AfxMessageBox("创建ms_word服务失败");
return;
}
try
{
docs = wordApp.GetDocuments();
doc = docs.Open(vFileName,vFalse,vFalse,vFalse,
varstrNull,varstrNull,vFalse,varstrNull,
varstrNull,vFalse,vFalse,vFalse);
pgraphs = doc.GetParagraphs();
for(i=1; i<pgraphs.GetCount(); i++)
{
pgraph = pgraphs.Item(i);
range = pgraph.GetRange();
COleVariant vt = pgraph.GetStyle();
vt.ChangeType(VT_BSTR,NULL);
CString str = vt.bstrVal;
TRACE("style = %s\n",str);
}
}
catch(COleException *e)
{
LPVOID lpMsg;
::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, NULL, e->m_sc,
MAKELANGID(LANG_NEUTRAL,
SUBLANG_DEFAULT),(LPTSTR) &lpMsg,
0, NULL);
::MessageBox(NULL, (LPCTSTR)lpMsg, "COM Error",
MB_OK | MB_SETFOREGROUND);
::LocalFree( lpMsg );
}
catch(COleDispatchException *e)
{
char msg[512];
sprintf(msg, "Run-time error '%d':\n\n%s",
e->m_scError & 0x0000FFFF, e->m_strDescription);
::MessageBox(NULL, msg, "Server Error",
MB_OK | MB_SETFOREGROUND);
}
wordApp.Quit(vFalse,vLong,vLong);
解决方案1:
关注!
解决方案2:我以前遇到过,这是word的一个bug,在.net中有解决方案!看看MSDN