现在的位置: 首页 > 综合 > 正文

VC 6下word操作心得-将文字写入word

2013年10月22日 ⁄ 综合 ⁄ 共 1077字 ⁄ 字号 评论关闭

 

(1)  生成Dialog时,要选择ActiveX;

(2)  在initdialog中初始化OLE环境

BOOL CDialogTestDlg::OnInitDialog() 中添加

if(!AfxOleInit())
     {
       AfxMessageBox("OLE Initialization Failed");
       return FALSE;
     }

(3)  View->ClassWizard->Automation->Add Class From Library:定位到你安装Office的目录找到MSWord.Olb(我的word版本是word2007)

添加_Application, Documents, Selection三个类即可,注意,不能像有些文章中说的把所有类都添加,否则会编译不通过。

在用到的.CPP文件中添加头文件,比如我的button消息响应函数在xxxDlg.cpp中,就在文件中添加#include "msword.h";#include <atlbase.h>。

然后,加入下面的代码即可(这段代码是参考网上的)

    // TODO: Add your control notification handler code here

    _Application app;

    COleVariant vTrue((short)TRUE), vFalse((short)FALSE);

    app.CreateDispatch(_T("Word.Application"));

    app.SetVisible(FALSE);

    //Create New Doc

    Documents docs=app.GetDocuments();

    CComVariant tpl(_T("")),Visble,DocType(0),NewTemplate(false);

    docs.Add(&tpl,&NewTemplate,&DocType,&Visble);

    //Add Content:Text

    Selection sel=app.GetSelection();

    sel.TypeText(_T("\t\t\t\t\t \r\n"));

    sel.TypeText(_T("\t\t\t\t\t\t\t\t----------先来一个简单的\r\n"));

    sel.ReleaseDispatch();

    docs.ReleaseDispatch();

    app.SetVisible(TRUE);

    app.ReleaseDispatch();

抱歉!评论已关闭.