Delphi擅长做数据库类的MIS开发,但对于OA就有点力不从心了。不过随着Microsoft的COM技术逐渐成熟,现在普通Windows应用已经可以和Office 97无缝结合了,尤其是在Delphi 5中提供了一组Servers组件,更是简化了程序开发。
最近接触了一个用户的案例,用Delphi控制Word做一个合同管理程序。办公人员先根据业务需要,写好合同的文字,但在用户名称、产品名称等变化的位置填写指定的标记字符串,然后通过Delphi把数据库中的实际数据替换掉Word中的文字,最后让Word打印出合同。
Delphi自带了一个简单的Word例题,但功能太简单。通过查找VBA的说明,再对照Delphi的VCL,编写了如下代码,实现了基本的公文管理功能。
启动Word时用如下代码:
begin
try
Wordapplication.Connect;
except
MessageDlg(´Word may not be installed´, mtError, [mbOk], 0);
Abort;
end;
Wordapplication.Visible := True;
WordApplication.Caption := ´Delphi automation´;
end;
关闭Word用如下代码。如果想保存Doc文件,请修改SaveChanges变量的内容:
var
SaveChanges, OriginalFormat, RouteDocument: OleVariant;
begin
SaveChanges := WdDoNotSaveChanges;
OriginalFormat := UnAssigned;
RouteDocument := UnAssigned;
try
WordApplication.Quit(SaveChanges, OriginalFormat, RouteDocument);
WordApplication.Disconnect;
except
on E: Exception do
begin
Showmessage(E.Message);
WordApplication.Disconnect;
end;
end;
end;
让Word打开一个指定的文件,需要先放置OpenDialog,然后调用WordApplication.Documents.Open:
var
ItemIndex :OleVariant;
FileName, ConfirmConversions, ReadOnly, AddToRecentFiles,
PasswordDocument, PasswordTemplate, Revert,
WritePasswordDocument, WritePasswordTemplate, Format: OleVariant;
begin
if not dlgOpen.Execute then
Exit;
{Open document}
FileName := dlgOpen.FileName;
ConfirmConversions := False;
ReadOnly := False;
AddToRecentFiles := False;
PasswordDocument := ´´;
PasswordTemplate := ´´;
Revert := True;
WritePasswordDocument := ´´;
WritePasswordTemplate := ´´;
Format := wdOpenFormatDocument;
WordApplication.Documents.Open( FileName, ConfirmConversions,
ReadOnly, AddToRecentFiles, PasswordDocument, PasswordTemplate,
Revert, WritePasswordDocument, WritePasswordTemplate, Format );
{Assign WordDocument component}
ItemIndex := 1;
WordDocument.ConnectTo(WordApplication.Documents.Item(ItemIndex));
{Turn Spell checking of because it takes a long time if enabled and slows down Winword}
WordApplication.Options.CheckSpellingAsYouType := False;
WordApplication.Options.CheckGrammarAsYouType := False;
end;
让Word替换标记字符串要使用WordDocument.Range.Find.Execute,这里用Delphi替换了<#Name>:
var
FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike,
MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace: OleVariant;
begin
FindText := ´<#Name>´;
MatchCase := False;
MatchWholeWord := True;
MatchWildcards := False;
MatchSoundsLike := False;
MatchAllWordForms := False;
Forward := True;
Wrap := wdFindContinue;
Format := False;
ReplaceWith := ´Delphi´;
Replace := True;
WordDocument.Range.Find.Execute( FindText, MatchCase, MatchWholeWord,
MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward,
Wrap, Format, ReplaceWith, Replace );
end;
上面这4段代码完成了公文管理的基本功能,再把它和数据库结合起来,就可以开发一个与Lotus Notes类似的产品了。