_Application app;
Documents docs;
_Document doc;
Tables WordTables;
Table WordTable;
Cell WordCell;
Range WordRange;
Columns WordCols;
Rows WordRows;
if(!app.CreateDispatch("Word.Application"))
{
MessageBox("创建Word服务失败!",_T("提示"),MB_ICONERROR);
return;
}
docs.AttachDispatch(app.GetDocuments());
app.SetVisible(true);
//打开文件
IDispatch *dispatch=docs.Open(&_variant_t(_T("d://test.doc")),&vtMissing,&vtMissing,&vtMissing,
&vtMissing,&vtMissing,&vtMissing,&vtMissing,&vtMissing,&vtMissing,&vtMissing,
&vtMissing,&vtMissing,&vtMissing,&vtMissing);
if(dispatch)
{
doc.AttachDispatch(dispatch);
}
else
{//出错了
CString szErr="";
szErr.Format("打开文件出错,请查看文件是否存在!");
::AfxMessageBox(szErr);
//退出程序,释放对象
app.Quit(&vtMissing,&vtMissing,&vtMissing);
docs.ReleaseDispatch();
app.ReleaseDispatch();
return;
}
dispatch=doc.GetTables();
if(dispatch)
{
WordTables.AttachDispatch(dispatch);
}
else
{//出错了
CString szErr="";
szErr.Format("取得表格集合出错!");
::AfxMessageBox(szErr);
//退出程序,释放对象
app.Quit(&vtMissing,&vtMissing,&vtMissing);
docs.ReleaseDispatch();
app.ReleaseDispatch();
doc.ReleaseDispatch();
return;
}
int nTableCount=WordTables.GetCount();
if(nTableCount>0)
{
for(int i=1;i<=nTableCount;i++)
{
WordTable.AttachDispatch(WordTables.Item(i));
WordCols.AttachDispatch(WordTable.GetColumns());
WordRows.AttachDispatch(WordTable.GetRows());
int nCols=WordCols.GetCount();
int nRows=WordRows.GetCount();
for(int j=1;j<=nRows;j++)
{
for(int k=1;k<=nCols;k++)
{
dispatch=WordTable.Cell(j,k);
WordRange.AttachDispatch(dispatch);
CString szText=WordRange.GetText();
this->MessageBox(szText);
}
}
}
}
app.Quit(&vtMissing,&vtMissing,&vtMissing);
doc.ReleaseDispatch();
docs.ReleaseDispatch();
app.ReleaseDispatch();