DelPhi上传Excel(版本Delphi5 数据库Sql Server连接方式ADO/BDE)

Delphi5 实现excel上传资料给数据库

##控件支撑
个人使用到的控件OpenDialog;Button;DBnaviIgator;DBGrid
数据路连接:我是直接使用的table,所以我直接用的AdoTableDatasource 然后ADOQUERY调用函数赋值给DBGrid
##代码部分(直接使用button呼叫):
var
ExcelID,Sheet: Variant;
sFileName :String;
i,ExcelRowCount,OkNum,FailNum:integer;

Begin
OkNum:=0; //作为计算excel导入数据的行数计算 count excel rows
FailNum:=0; //监听excel导入过程中数据出错的行数–汇总 count All-Excel-Defeat-Rows
//下面开始导入数据 Import Data

   //触发上传事件 Call Opendialog Function for Update EXcel-File
with opendialog1 do
begin
  DefaultExt:='XLS';
  Filter:='Excel工作簿文件(*.XLS)|*.XLSX|*.XLS|*.CSV';   ---定义上传的文件必须符合某种规则
  if Execute then
  sFileName:=Filename
  else
    exit;

end;

// showmessage(label1.caption); //—for debug ignore it
// abort; //—for debug ignore it
with ADOQuery2 do //呼叫页面上的数据查询控件新建的为adoquery1以此类推,可以修改名称
begin
close;
SQL.Clear;
SQL.ADD(‘Truncate Table dbo.table’); //—这一段是为了插入表之前删除数据,不需要可屏蔽
ExecSQL; //BDE 就是close+open; use Bde-Connection is“close+open”
end ;
try
ExcelID:=CreateOleObject(‘Excel.Application’); //一般delphi程序会自带控件 ,delphi will contain this package
ExcelID.Visible:=False;
except
on E:Exception do
begin
ExcelID.Quit;
Application.Restore;
Application.BringToFront;
MessageBox(Self.Handle,Pchar(‘Caution!FileSource Error,cause’+e.Message),Pchar(AppliCation.Title),MB_OK+MB_ICONERROR); //固定写法
Exit;
end;
end;

try
  try
     ExcelID.WorkBooks.Open(sFileName);  //打开路径下文件(手动)。open file in path by owner
    //ExcelID.WorkBooks.Open('\\server\Public_Space\filepathe1\filepathe2\filepathe2.1\filepathe3\filename.CSV');
    Sheet:=ExcelID.WorkBooks[1].WorkSheets[1];   //read the first page in excel读取excel中第几页
    ExcelRowCount:=ExcelID.WorkSheets[1].UsedRange.Rows.Count; //get the line counts  获取excel的行数
    NTADO.BeginTrans;
    for i:=2 to ExcelRowCount do
    begin
      if length(trim(Sheet.Cells[i,1].Value))<=0 then break;   //判定excel中内容行数需要大于2行 adjust the rows in the excel page
      with AdoQuery1 do
      begin 
        if eof then
        begin
          close;
          SQL.Clear;
          SQL.Add('Insert into table') ;
          SQL.Add(' values('''+inttostr(OkNum)+''','''+string(Sheet.Cells[i,1].Value)+''',' );
            SQL.Add(''''+string(Sheet.Cells[i,2].Value)+''','''+string(Sheet.Cells[i,3].Value)+''',' );
            SQL.Add(''' '','' '','' '','' '','' '','' '','' '','' '','' '','' '','' '','' '','' '','' '','' '','' '' )' )   ; //这里是插入了20个栏位的表--insert line copy by table to excel
            ExecSQL;
            OkNum:=OkNum+1;
        end
        else
            FailNum:=FailNum+1;
      end;
    end;
     NTADO.CommitTrans;//提交事务 upload the business
     label1.caption:= '文件路径';
     MessageBox(Self.Handle,Pchar('系统提示:'+IntToStr(OkNum+FailNum)+'条数据,其中'+IntToStr(FailNum)+'有历史记录,'+IntToStr(OkNum)+'成功导入!'),
                                     Pchar(AppliCation.Title),MB_OK+MB_ICONINFORMATION);

  except
      on E:Exception do
      begin
        NTADO.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;
    Application.Restore;
    Application.BringToFront;
    ADOTable1.Active:=false;//这是我自己的伴生刷新事件
    AdoTable1.Active:=True;//这是我自己的伴生刷新事件
   end;
End

纯手打!点个赞吧!!!

你可能感兴趣的:(UTPCB)