delphi中把EXCEL中的数据导入到SQL中
2009-01-06 21:44

一直都是将数据从SQL导入到EXCEL文件,前两天因为有需求,试着将EXCEL文件导入到SQL,才发现两者的原理其实是一样的,如下代码,并附注释:

procedure Tfom1.ExcelToSQLMenuItemClick(Sender: TObject);
var
ExcelID,Sheet: Variant;
sFileName :String;
i,ExcelRowCount,OkNum,FailNum:integer;
begin
//指定文件
OkNum:=0;   //导入成功的数据
FailNum:=0; //导入失败的数据

    //指定要导入的EXCEL文件
   With hrSysDataModule.MyOpenDialog do
    begin
     DefaultExt:='Xls';
     Filter :='Excel工作簿文件(*.xls)|*.Xls';
     if Execute then
         sFileName := FileName
     else
         exit;
    end;

    Try
        ExcelID := CreateOleObject( 'Excel.Application' );
        ExcelID.Visible :=False; //若为true,则将显示并打开将要导入的excel文件
   except
      on E: Exception do
      begin
        ExcelID.Quit;
        ExcelID := Unassigned;
        Application.Restore;
        Application.BringToFront;
        MessageBox(Self.Handle,Pchar('系统提示您,创建Excel对象出错,原因为:'+ e.Message), Pchar(AppliCation.Title),MB_OK+MB_ICONERROR);
        Exit;
      end;
   end;

   try
      Try
        ExcelID.WorkBooks.Open(sFileName);
        Sheet:= ExcelID.WorkBooks[1].WorkSheets[1];
//        ExcelColCount := ExcelID.WorkSheets[1].UsedRange.Columns.Count;
        ExcelRowCount := ExcelID.WorkSheets[1].UsedRange.Rows.Count; //获得本数据表有多少行数据
        ADOConnection1.BeginTrans; //开始事务
        for i :=2 to ExcelRowCount do   //将要从哪行开始读,本程序为从第二行开始读,第一行为标题
        begin
          if length(trim(Sheet.Cells[i,1 ].Value)) <=0 then break;   //如果第一个单元格为空,则提前结束循环,此处也可以用其它方式结束
          With ADOQuery1 do
          begin
              close;
              SQL.Clear;
              SQL.Add('Select * from table1 where keyid like '''+Sheet.Cells[i,3 ].Value+''''); //此处指定每行第三单元格的内容为关键字,不得有重复,若有重复,则该行的数据不导入
              Open;
              if eof then
              begin
                Close;
                SQL.Clear;
                SQL.Add('Insert into table1(hrname,nameEn,sex,keyid,birthday)');
        {        SQL.Add(' values(:hrname,:nameEn,:sex,:shenfz,:birthday)');
                Parameters.parambyname('hrname').Value :=Sheet.Cells[i,1].Value;
                Parameters.parambyname('nameEn').Value :=UpperCase(getpy1(Sheet.Cells[i,1].Value));    // getpy1函数是以取得姓名的首拼
                Parameters.parambyname('sex').Value :=Sheet.Cells[i,2].Value;
                Parameters.parambyname('shenfz').Value:= String(Sheet.Cells[i,3 ].Value);

                if checkisdate(trim(Sheet.Cells[i,4 ].Value)) then        //检查是不是日期格式
                    Parameters.parambyname('birthday').Value:=null
                else
                    Parameters.parambyname('birthday').Value:= Sheet.Cells[i,4 ].Value;
              } //该处括住部分为一种方式

                SQL.Add(' values('''+string(Sheet.Cells[i,1].Value)+''','''+UpperCase(getpy1(string(Sheet.Cells[i,1].Value)))+''',' );
                SQL.Add(''''+string(Sheet.Cells[i,2].Value)+''','''+string(Sheet.Cells[i,3].Value)+''',' );
                if checkisdate(trim(string(Sheet.Cells[i,4 ].Value))) then
                   SQL.Add(''''+string(Sheet.Cells[i,4].Value)+ ''',' )
                else
                   SQL.Add('null,' );

                SQL.Add(''''+string(Sheet.Cells[i,5].Value)+''')' );
                ExecSQL;
                OkNum:=OkNum+1;   //导入成功数加1
              end
              else
                FailNum:=FailNum+1; //若库已有相应的关键字记录,则导入失败数加1

          end;
        end;
          ADOConnection1.CommitTrans; //提交事务
          MessageBox(Self.Handle,Pchar('系统提示您:系统共成功导入'+IntToStr(OkNum+FailNum)+'条信息,其中'+IntToStr(FailNum)+'条信息系统内已有记录,'+IntToStr(OkNum)+'条信息成功导入!'),
                                         Pchar(AppliCation.Title),MB_OK+MB_ICONINFORMATION);
       except
         on E: Exception do
         begin
           ADOConnection1.RollbackTrans; //报错,回滚事务
           MessageBox(Self.Handle,Pchar('系统提示您,数据导入失败,原因为:'+e.Message),
                                         Pchar(AppliCation.Title),MB_OK+MB_ICONERROR);
         end;
       end
   finally
      ExcelID.WorkBooks[1].Close(false,'');
      ExcelID.Quit;
      ExcelID := Unassigned;
      sheet := Unassigned;
      Application.Restore;
      Application.BringToFront;
      RefreshButton.Click;
   end;
end;

function TForm1.checkisdate(datastring :String):boolean; //检查是不是日期
var
year,month,day:word;
begin
      try
          DecodeDate(StrToDateTime(datastring),year,month,day); //先看能否转换为日期格式,且分解为年月日
          if length(datastring)>=8 then    // 即使上句不报错,也得查看是不是类似为0:0:0这样的格式,也是错的,此处检查长度
             Result := True
          else
             Result := False;
            
          if Result then   //若以上结果为正确,,本程序还要检查是不是大于1950年
          if year > 1950 then
             Result := True
          else
             Result := False;
            
      except
          Result   :=   False;
      end;
end;