最近帮同学用Delphi 7写的一个数据库应用中的一个功能是将查询的结果导出到一个Word文档中保存。虽然Delphi 7的Servers面板中提供了TWordApplication和TWordDocument组件,但是帮助中却几乎没有写它们的使用方法。于是在中国期刊网上down了许多的相关文章来看,只可惜几乎都是用Delphi 5写的(Delphi 7中不能兼容),而且都只是简单的介绍了一下,甚是郁闷。在经过一天的摸索之后终于用Delphi 7实现了这个功能。代码如下:
//uses Word2000, ComObj;
//WordApp: TWordApplication;
//WordDoc: TWordDocument;
procedure TfrmDetails.btnExportClick(Sender: TObject); //单击“导出“按钮
var
V:Variant;
Template,NewTemplate,DocumentType,Visible:OleVariant;
itemIndex:OleVariant;
fileName:Olevariant;
NoPrompt,OriginalFormat:OleVariant;
RouteDocument,SaveChanges:OleVariant;
begin
//指定文档的路径和文件名
fileName:='C:\LogAdmin\doc\'+'值班日志'+Trim(DBTextID.Caption)+'.doc';
//如果该日志的对应Word文档已经存在则提示是否覆盖
if FileExists(fileName)=true then
begin
Beep;
if Application.MessageBox('文档已经存在,是否覆盖?','警告',MB_OKCANCEL)=IDCANCEL then
Abort;
end;
//测试当前是否运行了Word 2000
try
V:=GetActiveOleObject('Word.Application');
except
//未运行则运行之
V:=CreateOleObject('Word.Basic');
end;
try
//连接到Word 2000
WordApp.Connect;
except
Beep;
MessageDlg('不能生成文档,请确认是否安装了Word 2000!',mtError,[mbOK],0);
Abort;
end;
//显示Word 2000
WordApp.Visible:=true;
//给调用Add函数使用的实参赋值
Template:=EmptyParam;
NewTemplate:=False;
DocumentType:=wdNewBlankDocument;
Visible:=true;
//调用Add函数
WordApp.Documents.Add(Template,NewTemplate,DocumentType,Visible);
//连接到新建的文档
itemIndex:=1;
WordDoc.ConnectTo(WordApp.Documents.Item(itemIndex));
//文档另存为
WordDoc.SaveAs(fileName);
//开始向Word文档中写入内容
with WordApp.Selection do
begin
Font.Size:=20;
Font.Bold:=2;
Paragraphs.Alignment:=wdAlignParagraphCenter;
TypeText('值班日志详细内容');
TypeParagraph; //换行
TypeParagraph;
Font.Size:=12;
Font.Bold:=0;
Paragraphs.Alignment:=wdAlignParagraphLeft;
TypeText('编号: '+DBTextID.Caption);
TypeParagraph;
TypeText('日期: '+DBTextDate.Caption);
TypeParagraph;
TypeText('温度: '+DBTextT.Caption);
TypeParagraph;
TypeText('湿度: '+DBTextH.Caption);
TypeParagraph;
TypeText('天气: '+DBTextWeather.Caption);
TypeParagraph;
TypeText('值班人: '+DBTextName.Caption);
TypeParagraph;
TypeText('值班时间:'+DBTextTime.Caption);
TypeParagraph;
TypeText('有无异常:'+lbException.Caption);
TypeParagraph;
TypeText('使用工具:');
TypeParagraph;
TypeText(DBMemoTool.Text);
TypeParagraph;
TypeText('现场环境:');
TypeParagraph;
TypeText(DBMemoEnv.Text);
TypeParagraph;
TypeText('记录一: ');
TypeParagraph;
TypeText(DBMemoR1.Text);
TypeParagraph;
TypeText('记录二: ');
TypeParagraph;
TypeText(DBMemoR2.Text);
TypeParagraph;
TypeText('记录三: ');
TypeParagraph;
TypeText(DBMemoR3.Text);
TypeParagraph;
TypeText('备注: ');
TypeParagraph;
TypeText(DBMemoMemo.Text);
TypeParagraph;
end;
//保存文档
NoPrompt:=false;
OriginalFormat:=wdOriginalDocumentFormat;
WordApp.Documents.Save(NoPrompt,OriginalFormat);
//关闭文档
SaveChanges:=wdSaveChanges;
OriginalFormat:=wdOriginalDocumentFormat;
RouteDocument:=false;
WordApp.Documents.Close(SaveChanges,OriginalFormat,RouteDocument);
//断开和Word 2000的连接
WordApp.Disconnect;
MessageDlg('日志内容导出成功!保存为'+fileName,mtInformation,[mbOK],0);
//关闭窗体
frmDetails.Close;
end;
本文地址:http://com.8s8s.com/it/it4832.htm