Delphi- 操作EXCEL

  因工作需要,需要到操作EXCEL,先了解一下怎么读取EXCEL这个,做了一个DEMO,备注在这里

  一、读取EXCEL

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls,ComObj;

type
  TForm1 = class(TForm)
    btn1: TButton;
    dlgOpen1: TOpenDialog;
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
var
  ExcelApp,WorkBook: Olevariant;
  ExcelRowCount,i:Integer;
  strName,strAge:string;
begin

  if dlgOpen1.Execute then
  begin

    ExcelApp := CreateOleObject('Excel.Application');
    WorkBook := ExcelApp.WorkBooks.Open(dlgOpen1.FileName);

    ExcelRowCount := WorkBook.WorkSheets[1].UsedRange.Rows.Count;
    //ShowMessage(IntToStr(ExcelRowCount));

    for i:=1 to ExcelRowCount+1 do
    begin
      strName:= ExcelApp.Cells[i,1].Value;
      strAge:= ExcelApp.Cells[i,2].Value;

      {如果有一行为空,则退出}
      if ((strName='') and (strAge='')) then
         exit
      else
      begin
      
        ShowMessage(strName);
        ShowMessage(strAge);

      end;


    end;


  end;

  {最后关闭连接}
  WorkBook.Close;
  ExcelApp.Quit;
  ExcelApp := Unassigned;
  WorkBook := Unassigned;


end;

end.

  

  读取出数据,插入数据库的语句,在网上百度到的。

  with query1 do         
  begin          
      close;          
      sql.clear;sql.add(insert into test(name,address) values(:name,:address));
      parambyname('name').asstring := excelx;
      parambyname('address').asstring := excely;
      execsql;         
   end;