Delphi 导Excel 到 Sqlserver

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, DB, ADODB,Excel2000,ComObj, Grids, DBGrids;

type
  TForm1 = class(TForm)
    Button1: TButton;
    OpenDialog1: TOpenDialog;
    Edit1: TEdit;
    Button2: TButton;
    ADOQuery1: TADOQuery;
    ADOConnection1: TADOConnection;
    DBGrid1: TDBGrid;
    DataSource1: TDataSource;
    Label1: TLabel;
    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);
begin
  OpenDialog1.Title := '请选择正确的excel文件';
  OpenDialog1.Filter := 'Excel(*.xls) ?*.xls';
  if OpenDialog1.Execute then
  edit1.Text := OpenDialog1.FileName;

end;

procedure TForm1.Button2Click(Sender: TObject);
const
    BeginRow = 2; BeginCol = 1;
var
    Excel: OleVariant;
    iRow,iCol : integer;
    xlsFilename: string;
begin
   if (trim(edit1.Text) = '') then
  begin
    application.MessageBox('请选择正确的excel路径', '错误信息', MB_ICONERROR+MB_OK);
    exit;
  end;
  xlsFilename := trim(edit1.Text);
    try
        Excel := CreateOleObject('Excel.Application');
    except
        Application.MessageBox('excel没有安装', '提示信息', MB_OK+MB_ICONASTERISK+MB_DEFBUTTON1+MB_APPLMODAL);
        Exit;
    end;
    Excel.Visible := false;
    Excel.WorkBooks.Open(xlsFilename);
    try
        iRow := BeginRow;
        iCol := BeginCol;

        while trim(Excel.WorkSheets[1].Cells[iRow,iCol].value) <> '' do begin
            with ADOQuery1 do begin
                Append;
                Fields[0].AsString := trim(Excel.WorkSheets[1].Cells[iRow,iCol].value);
                Fields[1].AsString := trim(Excel.WorkSheets[1].Cells[iRow,iCol+1].value);
                Fields[2].Asstring := trim(Excel.WorkSheets[1].Cells[iRow,iCol+2].value);
                iRow := iRow + 1;
            end;

  end;
        Excel.Quit;
        ADOQuery1.UpdateStatus ;
    except
        Application.MessageBox('导入数据出错', '提示信息', MB_OK+MB_ICONASTERISK+MB_DEFBUTTON1+MB_APPLMODAL);
        Excel.Quit;
    end;
  MessageBox(GetActiveWindow(), '数据导入成功', '提示信息', MB_OK+MB_ICONWARNING);

end;

end.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值