唐
唐宗
Unregistered / Unconfirmed
GUEST, unregistred user!
以下是我做的一段代码,主要用于用CBC控制写入WORD编制合同,发给大家共亨,也望大家不断的向里面加入内容.
代码:
#include <vcl.h>
#pragma hdrstop
#include "oleWORD.h"
#include <comobj.hpp>
#include <dir.h>
#include <utilcls.h>
#include "Word_2k_SRVR.h"
//加入这两个,否则在调用如wdSeekCurrentPageFooter参数时会报错
#include "Word_2k.h"
#define OPG OlePropertyGet //命令太长了,简化一下
#define OPS OlePropertySet
#define OPR OleProcedure
#define OFN OleFunction
#pragma link "Word_2K_SRVR"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
Variant WordApp,WordDocs,WordDoc,WordRange,WordTable;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
char curdir[255];
current_directory(curdir);
AnsiString strFullFileName(curdir);
strFullFileName = strFullFileName + "//doc//contract.doc";
try
{
WordApp=GetActiveOleObject("Word.Application");
}
catch(...)
{
try
{
WordApp=Variant::CreateObject("Word.Application");
//建立WORD的OLE对象
}
catch(...)
{
Application->MessageBoxA("无法启动Word","错误提示!");
return;
}
}
WordApp.OlePropertySet("Visible",true);
//显示WORD程序界面
WordApp.OPG("Documents").OPR("Open",strFullFileName.c_str());
//打开文档,注意后面的文件要转为字符串
Variant WordActiveWindow=WordApp.OPG("ActiveWindow");
Variant WordActivePane =WordActiveWindow.OPG("ActivePane");
Variant WordView= WordActivePane.OPG("View");
WordView.OPS("SeekView",wdSeekCurrentPageFooter);
//选中文档的页脚
Variant WordSelection=WordApp.OPG("Selection");
WordSelection.OPR("TypeText",DateToStr(Date()).c_str());
Variant WordFormat=WordSelection.OPG("ParagraphFormat");
WordFormat.OPS("Alignment",wdAlignParagraphCenter);
//在文档中的页脚中插入日期
WordView.OPS("SeekView",wdSeekMainDocument);
//在WORD中将BOOKMARK替换成数据表中的内容
//Selection.GoTo What:=wdGoToBookmark, Name:="GHDW"
这句是WORD中的宏代码,为了对比和C++的不同,GHDW是WORD中的标签名
try{
Variant xx=WordSelection.Exec(Procedure("GoTo") << (int)wdGoToBookmark <<0 << 0 << "GHDW");
WordSelection.OPR("TypeText","中国");
}
catch(...)
{
Application->MessageBoxA("标签不存在!","错误提示!");
}
//在WORD中定位到第二个表格
// Selection.GoTo What:=wdGoToTable, Which:=wdGoToFirst, Count:=2, Name:=""
只要是GOTO,使用的参数和命令基本是一样的,同样可用于其他元素的查找.
WordSelection.Exec(Procedure("GoTo") << (int)wdGoToTable <<(int)wdGoToFirst << 2 << "");
// if(!WordApp.IsEmpty())
//{
// WordApp.OlePropertyGet("Application").OleProcedure("Quit");
// WordApp = Unassigned;
//}
}
//---------------------------------------------------------------------------
char __fastcall TForm1::current_directory(char *path)
{
strcpy(path, "X://");
path[0] = 'A' + getdisk();
getcurdir(0, path+3);
return(*path);
}