Excel文件导入MSSQL数据库

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, DB, ADODB, SMIBase, SMI2Cell, SMI2XLS, StdCtrls, ComObj,
  OleServer, ExcelXP, Grids, DBGrids;

type
  TForm1 = class(TForm)
    ADOConnection1: TADOConnection;
    tblTA: TADODataSet;
    DataSource1: TDataSource;
    Button1: TButton;
    DBGrid1: TDBGrid;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure ExcelToSqlserver(FileName : String);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  //IXLS
  ExcelToSqlserver('E:/dev.xls')
end;

procedure TForm1.ExcelToSqlserver(FileName: String);
var      
  I, J : Integer;      
  ExcelApplication1 : TExcelApplication;
  ExcelWorksheet1 : TExcelWorksheet;
  ExcelWorkbook1 : TExcelWorkbook;
begin
  try
      ExcelApplication1 := TExcelApplication.Create(Application);
      ExcelWorksheet1 := TExcelWorksheet.Create(Application);
      ExcelWorkbook1 := TExcelWorkbook.Create(Application);
      ExcelApplication1.Connect;
  except
      Application.Messagebox( 'Excel没有安装! ',  'Hello ', MB_ICONERROR + mb_Ok);
      Abort;
  end;
       
  Try
      ExcelWorkbook1.ConnectTo( ExcelApplication1.Workbooks.Open(FileName,EmptyParam,EmptyParam,
                                EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,
                                EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,0));
       
      ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks[1]);
      ExcelWorksheet1.ConnectTo(ExcelWorkbook1.Worksheets[1] as _worksheet);
  Except
      Exit;
  end;
  I := 2;//开始导入行数
  J := ExcelWorksheet1.UsedRange[1].Rows.Count;
  //J := ExcelWorksheet1.Cells.Count;
  try
      tblTA.Open;       //要导入的表
      while  I <= J do
      begin
          if Trim(ExcelWorksheet1.cells.item[i,1]) <> ' ' then
          begin
              tblTA.AppendRecord([
                      ExcelWorksheet1.Cells.Item[i,1],//第i行第1列.
                      ExcelWorksheet1.Cells.Item[i,2],//第i行第2列.
                      ExcelWorksheet1.Cells.Item[i,3] //第i行第3列.
                      ]);
          end
          else Break;
          Inc(I);
      end;
  finally
      tblTA.close;
      tblTA.Open;
      ShowMessage( '数据导入完毕! ');
  end;
       
  try
      ExcelApplication1.Disconnect;
      ExcelApplication1.Quit;
      ExcelApplication1.Free;
      ExcelWorksheet1.Free;
      ExcelWorkbook1.Free;
  except
      ShowMessage( '关闭出错! ');
  end;
end;

end.

你可能感兴趣的:(String,Excel,Integer,application,button,Forms)