DELPHI中四种EXCEL访问技术实现
⼀、引⾔
EXCEL在处理中⽂报表时功能⾮常强⼤,EXCEL报表访问也是信息系统开发中的⼀个重要内容,本⽂总结以往开发中所⽤到的⼏中EXCEL⽂件访问⽅法,在实际⼯作中也得到了很好的验证,本⽂列举了其中四种⽅法的实例与读者共享,程序已在W ⼆、ADO⽅式访问EXCEL⽂件
ADO⽅式访问EXCEL⽂件时,将EXCEL⽂件看作⼀个等同Oracle、MS SQLServer等数据库的⼀个ODBC数据源本⽂应⽤⽰例主要功能是打开EXCEL⽂件,并实现对EXCEL⽂件的编辑修改功能。实现过程及主要源代码如下:
1.在⼯程中新建窗⼝类TfrmADOEXCEL,在窗⼝中定义私有变量类型为TADOConnection的组件Conn,加⼊TADOTable组件ADOTabXLS、TDataSource组件DSXLS、TDBNavigator组件NavXLS 、TDBGrid组件GridXLS和TButton组件btnOpen,使2.编写btnOpen组件的OnClick事件。需要注意两点,Conn组件的Extend Properties属性要定义成excel 8.0,另外,EXCEL⽂件中的表单名“⼈员信息表”作为表明时要写成“[⼈员信息表$]”。
procedure TfrmADOEXCEL.btnOpenClick(Sender: TObject);
/
/打开EXCEL⽂件代码
begin
Conn:=TADOConnection.Create(nil);
Conn.ConnectionString:='Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+ExtractFileDir(Application.ExeName)+'/PersonData.xls;Extended Properties=excel 8.0;Persist Security Info=False';
Conn.LoginPrompt:=false;
Conn.Connected:=true;
ADOTabXLS.Connection:=Conn;
ADOTabXLS.TableName:='['+'⼈员信息表'+'$]';
ADOTabXLS.Active:=true;
DSXLS.DataSet:=ADOTabXLS;
GridXLS.DataSource:=DSXLS;
except;
FreeAndNil(Conn);
end;
end;
三、COM⽅式动态访问EXCEL⽂件
COM⽅式动态访问EXCEL⽂件时,基本⽅法是利⽤组件复⽤技术调⽤Office软件平台提供的COM服务组件,充分利⽤COM组件提供的⽅法操纵EXCEL⽂件。本⽂应⽤⽰例简单演⽰了如何利⽤COM技术将DataSet数据集的数据输出到EXCEL⽂件。实在⼯程中新建窗⼝类TfrmCOMEXCEL,在窗⼝中定义私有变量类型为TADOConnection的组件Conn,加⼊TADOTable组件ADOTabXLS和TButton组件btnOpen,使⽤btnOpen可以将数据输出到EXCEL⽂件。编写btnOpen组件的OnClick事件代码如下procedure TfrmCOMEXCEL.btnOpenClick(Sender: TObject);
var
XL: Variant; //打开EXCEL⽂件的Variant变量
Sheet: Variant;//指向EXCEL表单的Variant变量
RecNo,I: Integer;//记录数据表的当前记录号
begin
try
XL := CreateOleObject('Excel.Application');
XL.Visible := true;
if FileExists(ExtractFileDir(Application.ExeName)+'/test.xls') then
begin
XL.WorkBooks.Open(ExtractFileDir(Application.ExeName)+'/test.xls');
end
else XL.WorkBooks.Add;
XL.WorkBooks[XL.WorkBooks.Count].WorkSheets[1].Name := 'test';
Sheet := XL.WorkBooks[XL.WorkBooks.Count].WorkSheets[Trim('test')];
RecNo := 1;
ADOTabXLS.First;
while not ADOTabXLS.Eof do
begin
for I := 0to ADOTabXLS.FieldCount - 1do
if not (ADOTabXLS.Fields[I].DataType in [ftBlob, ftGraphic,
ftParadoxOle, ftDBaseOle, ftTypedBinary,
ftReference, ftDataSet, ftOraBlob, ftOraClob, ftInterface,
ftIDispatch]) then
begin
Sheet.Cells.NumberFormat := '@';
Sheet.Cells[RecNo, I+1] := ADOTabXLS.Fields[I].AsString;
sql语句实现的四种功能end;
Inc(RecNo);
ADOTabXLS.Next;
end;
try
XL.WorkBooks[XL.WorkBooks.Count].SaveAs(ExtractFileDir(Application.ExeName)+'/test.xls');
except ;
end;
end;
四、扩展OLEContainer⽅式访问EXCEL⽂件
在使⽤OLE⽅式访问EXCEL⽂件时,OLE容器在失去焦点会屏蔽正在访问的EXCEL⽂件操作;另外,使⽤in_place⽅式激活OLE容器时,会另外打开⼀个窗⼝,程序执⾏显得有些混乱,造成这些问题的主要原因是因为OLE容器响应了CM_UIDEACT type
TOleContainerEx=class(TOleContainer)
private
FJH: Boolean;
//重写CM_UIDEACTIVATE消息响应
procedure CMUIDeactivate(var Message: TMessage); message CM_UIDEACTIVATE;
published
property JH: Boolean read FJH write FJH;
end;
// 过程CMUIDeactivate的代码实现
procedure TOleContainerEx.CMUIDeactivate(var Message: TMessage);
begin
if not JH then
inherited;
end;
在使⽤TOLEContainerEx时,可采⽤临时创建的⽅式,也可进⼀步封装成可安装组建以便设计期使⽤。本⽂应⽤⽰例采⽤了临时创建的⽅式。在⼯程中新建窗⼝类TfrmEXOLEEXCEL,并定义Public变量 OleCon,类型为: TOleContainerEx;在窗⼝中procedure TfrmEXOLEEXCEL.btnOpenClick(Sender: TObject);
begin
//创建并显⽰扩展OLE类组件
OleCon := TOleContainerEx.Create(nil);
OleCon.Parent := Panel1;
OleCon.Align:=alClient;
OleCon.allowactivedoc := true;
OleCon.AllowInPlace := True;
OleCon.AutoActivate := aaGetFocus;
OleCon.Anchors := [akTop,akLeft,akRight,akBottom];
OleCon.Visible := True;
OleCon.SizeMode := smClip;
OleCon.CreateObjectFromFile(ExtractFileDir(Application.ExeName)+
'/PersonData.xls',false);
TOleContainerEx(OleCon).JH := True;
OleCon.SetFocus;
end;
五、DELPHI标准组件访问EXCEL⽂件
Delphi中封装了⼀组Microsoft Office⾃动化对象(Automation servers)。它使得我们很容易地把Office中的应⽤程序(Excel等)当作⼀个COM应⽤服务器进⾏控制。使⽤这组VCL组件可以在设计时进⾏属性设置,也可以在运⾏时动态访问EXCEL。利⽤标在⼯程中新建窗⼝类TfrmSTDCNTREXCEL,在窗⼝中加⼊TADOConnection组件ADOConnXLS,TADOTable组件ADOTabXLS、TButton组件btnOpen、TexcelApplication组件ExcelApplication1,TexcelWorkbook类组件ExcelWorkbook1和TExcelW procedure TfrmSTDCNTREXCEL.btnOpenClick(Sender: TObject);
var
aWorksheet: _WorkSheet;
tmpI,aRowIndex:integer;
aStr:string;
begin
ADOConnXLS.ConnectionString:='Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+ExtractFileDir(Application.ExeName)+'/PersonData.xls;Extended Properties=excel 8.0;Persist Security Info=False';
ADOConnXLS.LoginPrompt:=false;
ADOConnXLS.Connected:=true;
ADOTabXLS.Connection:=ADOConnXLS;
ADOTabXLS.TableName:='[⼈员信息表$]';
ADOTabXLS.Active:=true;
if ADOTabXLS.IsEmpty then exit;
Try
ExcelApplication1.Connect;
Except
MessageDlg('你还没有安装MicroSoft Excel,请先安装MicroSoft Excel!',mtError, [mbOk], 0);
Abort;
End;
ExcelApplication1.Visible[0]:=True;
ExcelApplication1.Caption := '新建EXCEL⽂件';
ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks.Add(EmptyParam,0));
aWorksheet:=ExcelWorkbook1.WorkSheets.Add(EmptyParam,EmptyParam,EmptyParam,EmptyParam,0) as _WorkSheet;
ExcelWorkSheet1.ConnectTo(aWorksheet);
aRowIndex:=1;
while not ADOTabXLS.Eof do
begin
for tmpI:=0to ADOTabXLS.FieldCount-1do
ExcelWorksheet1.Cells.Item[aRowIndex,tmpI+1]:=ADOTabXLS.FieldList[tmpI].AsString;
aRowIndex:=aRowIndex+1;
ADOTabXLS.Next;
end;
//保存EXCEL⽂件,并关闭EXCEL应⽤程序
Try
aStr:=ExtractFileDir(Application.ExeName)+'/EXCEL⽂件.xls';
ExcelWorkbook1.SaveAs(aStr,EmptyParam,EmptyParam, EmptyParam,EmptyParam,EmptyParam ,
xlNoChange ,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,0);
ExcelWorksheet1.Disconnect;
ExcelWorkbook1.Disconnect;
ExcelApplication1.Disconnect;
ADOTabXLS.Active:=false;
ADOConnXLS.Connected:=false;
except
ExcelWorksheet1.Disconnect;
ExcelWorkbook1.Disconnect;
ExcelApplication1.Disconnect;
ADOTabXLS.Active:=false;
ADOConnXLS.Connected:=false;
End;
end;
六、总结
综上所讲,本⽂分别举例讨论了EXCEL⽂件访问的⼏种⽅法,包括ADO、COM、扩展OLEContainer和DELPHI标准组件⽅式。在实际应⽤过程中,这⼏种⽅法也各有特⾊。ADO⽅式访问EXCEL⽂件适⽤于以数据库访问⽅式维护EXCEL⽂件,COM⽅

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。