Arsip: open Ms-Exell dari delphi


by yayaretina in Articles more 13 years ago 1862
with this code you can open a MS-Excel file (*.xls) in Delphi and access its fields and sheets without using any DBMS like BDE.
you must install ms-excel to use this code.
have a nice try....
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,comobj, Grids, ComCtrls, ExtCtrls, Buttons;
type
TForm1 = class(TForm)
OpenDialog1: TOpenDialog;
StringGrid1: TStringGrid;
Label1: TLabel;
Edit1: TEdit;
UpDown1: TUpDown;
Label2: TLabel;
Label3: TLabel;
Bevel1: TBevel;
BitBtn1: TBitBtn;
procedure UpDown1Click(Sender: TObject; Button: TUDBtnType);
procedure BitBtn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R .dfm}
procedure sh1(SheetIndex:integer);
Var
Xlapp1, Sheet:Variant ;
MaxRow, MaxCol,X, Y:integer ;
str:string;
begin
Str:=trim(form1.OpenDialog1.FileName);
XLApp1 := createoleobject('excel.application');  //Microsoft Excel 4.0 worksheet ( .xls)
  XLApp1.Workbooks.open(Str) ;
form1.UpDown1.Max:=strtoint(XLApp1.WorkSheets.count);
form1.Label3.Caption:= XLApp1.WorkSheets.count;
Sheet := XLApp1.WorkSheets[SheetIndex] ;
MaxRow := Sheet.Usedrange.EntireRow.count ;
MaxCol := sheet.Usedrange.EntireColumn.count;
form1.StringGrid1.RowCount:=maxRow+1;
form1.StringGrid1.ColCount:=maxCol+1;
for x:=1 to maxCol do
for y:=1 to maxRow do
form1.stringgrid1.Cells[x,y]:=sheet.cells.item[y,x].value;
XLApp1.Workbooks.close;
end;
procedure TForm1.UpDown1Click(Sender: TObject; Button: TUDBtnType);
begin
sh1(strtoint(edit1.Text));
end;
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
if opendialog1.Execute then begin
stringgrid1.Visible:=true;
edit1.Enabled:=true;
edit1.Text:='1';
label1.Enabled:=true;
label2.Enabled:=true;
label3.Enabled:=true;
updown1.Enabled:=true;
sh1(1);
end;
end;
end.
Syntax Highlighted with https://pascal-id.org/syntax
[red: buat semua penulis, mohon code yang ditulis di format dulu yahh..]
Local Business Directory, Search Engine Submission & SEO Tools FreeWebSubmission.com SonicRun.com