destructor TAppWord.Destroy();
begin
inherited Destroy();
end;
procedure TAppWord.WriteDoc(sts: Tstrings; fn: string);
var
sCnt: string;
i: integer;
begin
if (fn = '') or (not Assigned(sts)) then exit;
try
dbword.OpenFile(fn);
for i := 0 to sts.Count - 1 do
begin
if sts.Strings[i] = '' then
begin
sCnt := ' ';
dbword.Replace(ReplaceText+IntToStr(i),sCnt);
end
else
begin
sCnt := sts.Strings[i];
dbword.Replace(ReplaceText+IntToStr(i),sCnt);
end;
end;
dbword.Save;
dbword.CloseDoc;
except
raise(Exception.Create('error'));
end;
end;
function TAppWord.PickDoc(DocTitle: string; Conn: TADOConnection): string;
var
AQuery: TAdoQuery;
sqlDoc: string;
SD: TSaveDialog;
begin
result := '';
if (Conn = nil) or (DocTitle = '') or (not conn.Connected) then exit;
try
AQuery := TAdoQuery.Create(nil);
AQuery.Connection := Conn;
if AQuery.Active then AQuery.Close;
AQuery.SQL.Clear;
sqlDoc := Format('select MB_DATA from tdly.MB_WDWJ where MB_NAME=''%s''', [DocTitle]);
AQuery.SQL.Add(sqlDoc);
AQuery.Open;
if AQuery.RecordCount <> 1 then
begin
Alert('无法提取'+ DocTitle +'模板文件');
exit;
end;
SD := TSaveDialog.Create(nil);
try
SD.Filter := 'WORD文件(*.DOC)|*.DOC';
sd.DefaultExt := '*.doc';
sd.Options := [ofPathMustExist, ofOverwritePrompt];
if not SD.Execute then exit;
result := Sd.FileName;
Tblobfield(AQuery.FieldByName('MB_DATA')).SaveToFile(Result);// .SaveToStream(memstr); //模板字段
finally
AQuery.Close;
AQuery.Free;
SD.Free;
end;
except
end;
end;
启动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;
{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;