频道分类

Delphi 加载Excel 导入数据库

作者:admin 来源: 日期:2020/2/10 13:44:42 人气: 标签:

 
uses  ComObj;

procedure TForm1.Button1Click(Sender: TObject);
const
  ESatir = $0000000B;
var
  Adet: Integer;
  Book: Variant;
  SSay, j, I: Integer;
  Excel, Sheet: Variant;
begin
  Adet := 0;

  OpenDialog.Filter := 'Excel *.xls,*.xlsx|*.xls;*.xlsx';
  OpenDialog.Options := OpenDialog.Options + [ofAllowMultiSelect];
  if OpenDialog.Execute then
  begin
    for I := 0 to OpenDialog.Files.Count - 1 do
    begin
      Excel := CreateOleObject('Excel.Application');
      Book := Excel.WorkBooks.Open(OpenDialog.Files[I]);
      Sheet := Book.WorkSheets['Master']; // Sayfa adı
      SSay := Excel.ActiveSheet.Cells.SpecialCells(ESatir, EmptyParam).Row;
      try
        With FDQuery do
        begin
          for j := 5 to SSay do
          begin
            Inc(Adet);
            Close;
            SQL.Clear;
            SQL.Add('Insert Into LIST (SIRANO, GIRIS, IDADI, URUN)');
            SQL.Add(' Values (:SR, :GR, :IA, :UR)');
            ParamByName('SR').AsInteger := Adet;
            ParamByName('GR').Value := Sheet.Cells[j, 2].Text;
            ParamByName('IA').Value := Sheet.Cells[j, 3].Text;
            ParamByName('UR').Value := Sheet.Cells[j, 4].Text;
            ExecSQL;
Application.ProcessMessages;
          end;
        end;
      finally
        Screen.Cursor := crDefault;
        Excel.WorkBooks.Close;
        Excel.Quit;
        Excel := Unassigned;
        Sheet := Unassigned;
      end;
    end;
  end;
  FDQuery.Close;

end;

end;