频道分类

Delphi ADOConnection1 连接excel 读取数据

作者:admin 来源: 日期:2020/1/30 1:27:35 人气: 标签:

 
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Data.DB, Data.Win.ADODB,
  Vcl.Grids, Vcl.DBGrids;

type
  TForm1 = class(TForm)
    OpenDialog1: TOpenDialog;
    Button1: TButton;
    Edit1: TEdit;
    ADOConnection1: TADOConnection;
    ComboBox1: TComboBox;
    ADOQuery1: TADOQuery;
    Memo1: TMemo;
    Button2: TButton;
    DataSource1: TDataSource;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  fn:string;
begin
  if OpenDialog1.Execute then
  begin
    Edit1.Text := OpenDialog1.FileName;
    fn := Edit1.Text;
    Screen.Cursor := crHourGlass;
    try
      ADOConnection1.Close;
      ADOConnection1.ConnectionString := 'Provider=Microsoft.ACE.OLEDB.12.0;Data Source='+fn+';Extended Properties= Excel 12.0;Persist Security Info=True';
      ADOConnection1.Connected := True;
      ADOConnection1.GetTableNames(ComboBox1.Items);




    finally
      Screen.Cursor := crDefault;
    end;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
i:integer;
begin
    ADOConnection1.LoginPrompt:=false;
    ADOConnection1.Connected:=true;
    ADOQuery1.Connection:=ADOConnection1;
    ADOQuery1.close;
    ADOQuery1.SQL.Clear;
    ADOQuery1.SQL.add('select * from ['+ComboBox1.Text+']');
    ADOQuery1.Active:=true;


     try
    while not ADOQuery1.Eof do
    begin

      for i := 0 to ADOQuery1.FieldCount -1 do
      begin
        memo1.Lines.Add(ADOQuery1.Fields[i].AsString);
      end;

      ADOQuery1.Next;
    end;
  finally

  end;



end;

end.