欢迎yis
方法1:
用delphi自带的控件
procedure Tfrm_exportword.ConnectWord;
begin
try
Wordapplication.Connect;
except
MessageDlg('Word可能没有安装!', mtError, [mbOk], 0);
Abort;
end;
Wordapplication.Visible := True;
WordApplication.Caption := 'Delphi automation';
end;
方法2 ole:
procedure connect;
begin
try
Word_Handle := GetActiveOleObject('Word.Application');
except
try
Word_Handle := CreateOleObject('Word.Application');
except
Exit;
end;
end;
Word_Handle.Visible := True;
Doc_Handle := Word_Handle.Documents.open(FileName := 'C:/text.doc');
end;
方法3 com:参考的是yzhshi的代码:
$80000000是excel,不知word 的代码是多少?
function Connect_Excel: Boolean;
{连接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;
var
l_Excel_Handle: IDispatch;
begin
if FShow_Progress = True then
begin
Create_Run_Excel_Form(nil);
FRun_Excel_Form.Show;
end;
if My_GetActiveOleObject('word.Application', l_Excel_Handle) = False then
if My_CreateOleObject('word.Application', l_Excel_Handle) = False then
begin
FRun_Excel_Form.Free;
FRun_Excel_Form := nil;
raise exception.Create('启动word失败,可能没有安装Excel!');
Result := False;
Exit;
end;
FExcel_Handle := l_Excel_Handle;
if FShow_Progress = True then
begin
FRun_Excel_Form.Free;
FRun_Excel_Form := nil;
end;
Result := True;
end;
function New_Worddoc: Boolean;
var
i: Integer;
begin
Result := True;
try
FWorkbook_Handle := FExcel_Handle.Documents.Add;
except
raise exception.Create('新建word文档出错!');
Result := False;
Exit;
end;
end;
我想第三中方法可能最快。但不知如何实现。