我也这样用:参考一下我的代码:
procedure ImpDataToWord(DataSet: TDataSet; sFileName, sTitle: string; const
Fields: array of string; fOther: TField = nil);
{连接Ole对象}
function My_GetActiveOleObject(const ClassName: string; out
Ole_Handle: IDispatch): Boolean;
var
//IDispatch
ClassID: TCLSID;
Unknown: IUnknown;
l_Result: HResult;
begin
Result := False;
l_Result := CLSIDFromProgID(PWideChar(WideString(ClassName)),
ClassID);
if (l_Result and $80000000) = 0 then
begin
l_Result := GetActiveObject(ClassID, nil, Unknown);
if (l_Result and $80000000) = 0 then
begin
l_Result := Unknown.QueryInterface(IDispatch, Ole_Handle);
if (l_Result and $80000000) = 0 then
Result := True;
end;
end;
end;
{创建OLE对象}
function My_CreateOleObject(const ClassName: string; out
Ole_Handle: IDispatch): Boolean;
var
ClassID: TCLSID;
l_Result: HResult;
begin
Result := False;
l_Result := CLSIDFromProgID(PWideChar(WideString(ClassName)),
ClassID);
if (l_Result and $80000000) = 0 then
begin
l_Result := CoCreateInstance(ClassID, nil, CLSCTX_INPROC_SERVER
or
CLSCTX_LOCAL_SERVER, IDispatch, Ole_Handle);
if (l_Result and $80000000) = 0 then
Result := True;
end;
end;
//替换指定的数据
procedure ReplaceData(ObjH: Variant; const SourceText, DestText: string);
begin
ObjH.Selection.Find.Replacement.ClearFormatting;
ObjH.Selection.Find.Text := SourceText;
ObjH.Selection.Find.Replacement.Text := DestText;
ObjH.Selection.Find.Forward := True;
ObjH.Selection.Find.Wrap := 1;
ObjH.Selection.Find.Format := False;
ObjH.Selection.Find.MatchCase := False;
ObjH.Selection.Find.MatchWholeWord := False;
ObjH.Selection.Find.MatchByte := True;
ObjH.Selection.Find.MatchWildcards := False;
ObjH.Selection.Find.MatchSoundsLike := False;
ObjH.Selection.Find.MatchAllWordForms := False;
ObjH.Selection.Find.Execute(Replace := 1);
end;
//----------------------ImpDataToWord Begin------------------------------//
const
Obj_Name = 'Word.Application';
ErrMsg = '启动Word失败,可能没有安装Word!';
var
l_Excel_Handle: IDispatch;
ObjH: Variant;
i: integer;
begin
if not My_GetActiveOleObject(Obj_Name, l_Excel_Handle) then
if not My_CreateOleObject(Obj_Name, l_Excel_Handle) then
begin
raise exception.Create(ErrMsg);
Exit;
end;
ObjH := l_Excel_Handle;
ObjH.Documents.Open(FileName := vp_SystemPath + '/' + sFileName);
for i := 0 to High(Fields) do
ReplaceData(ObjH, Fields, DataSet.FieldByName(Fields).AsString);
//指定特殊的字段数据
if fOther <> nil then
ReplaceData(ObjH, fOther.FieldName, fOther.AsString);
ObjH.ActiveDocument.SaveAs(FileName := vp_DesktopPath + '/' + sTitle);
ObjH.ActiveDocument.PrintPreview;
ObjH.Visible := True;
ObjH.ActiveWindow.ActivePane.View.Zoom.Percentage := 100;
end;
//----------------------ImpDataToWord End----------------------------------//