用word做delphi报表输出工具
整理编辑:china asp
笔者在实际应用中发现,报表的内容一般很少变动,但其字体格式及版式是经常变动的,而且有时用户为了某种需要,不想修改数据库的真实内容而又要改变报表内容。如果用reportsmith可以解决前者问题,但对于后者则无能为力了,且其界面是英文的,不合用户习惯。如果用3.0中的tqreport的报表部件,则两者都不能实时解决,必须修改原代码后重新编译才能使用。而使用word及excel则完全可以克服以上不足。具体实现如下(以word实现为例):
首先用word编辑报表格式,并排好版,把将要输出的数据项用表单域代替,并取名。这里我们暂时假设有表单域item1及item2(均为文本型),将这个文档存为模板文件example.dot,然后按如下步骤进行:
1)运行delphi3,在form1里加入一个system部件集里的tddeclientcov部件,取名为ddeexample,将其connectmode设为ddemanual(手动方式);将ddeservice设为‘(winword)’;将serviceapplication设为‘winword’。
2)编写一个自定义过程,以激活word,如下:
procedure tform1.wordactive(cmds: tstrings);
var
wordpath: string;
begin
if(not ddeexample.openlink) then {判断是否巳动态链接}
begin
if(findwindow('opusapp', nil)=0) then
begin
wordpath := 'c:\msoffice\winword';
if(wordpath='') then
showmessage('中文word未安装或未设置路径,请安装设置word中文 版。')
else begin
ddeexample.serviceapplication := wordpath+'\winword.exe';
if(ddeexample.openlink) then {如果巳动态链接执行宏命令}
ddeexample.executemacrolines(cmds,false)
else
showmessage('无法启动word中文版!');
ddeexample.serviceapplication := 'winword.exe';
end;
end
else begin{如果巳动态链接执行宏命令}
ddeexample.executemacrolines(cmds,false);
end;
end
else
ddeexample.executemacrolines(cmds,false);
end;
在private声明区里加入如下:
procedure activeword(cmds: tstrings);
3)在form1中加入一个按钮button1,在其onclick事件里写如下代码:
procedure tform1.button1click(sender: tobject);
var
cmds:tstringlist;{创建cmds}
tempitem1,tempitem2:string;
begin
cmds:=tstringlist.create;
cmds.clear;
tempitem1:='数据项一';
tempitem2:='数据项二';
with cmds do
begin
clear;
add('[filenew.template ="example.dot″]');{打开模板文件example.dot}
add('[appmaximize]');{文档最大化}
add('[setformresult"item1″,″'+tempitem1+'″]');{将数据tempitem1传给表单域item1}
add('[setformresult"item2″,″'+tempitem2+'″]);{将数据tempitem2传给表单域item2}
end;
wordactive(ddeexample,cmds);{调用自定义过程}
cmds.free;{释放cmds}
end;
运行这个程序,单击button1,大家可以发现word被启动了,屏幕上出现了:数据项一;数据项二两个数据项。最后,大家可以任意修改本报表的格式及数据,因为这时这个报表与具体的应用程序巳没有关系了。
本例中用的是中文word6或中文word7。由于word97的宏命令巳变为visual basic语句,如大家想用word97实现,请将其宏命令改变为相应的代码。
这是个简单的示例,大家可以利用word的宏录制功能,录取更多的宏(如自动生成表格、填充文字、变动字体等宏命令),并与数据库的各种表联系起来,依次加入cmds中即可实现您所要求的更复杂的功能。