Delphi Excel導入 的通用程序 2.



Delphi Excel導入 的通用程序 .
分類: delphi 2012-09-24 18:20 257人閱讀 評論(0) 收藏 舉報
exceldelphiinteger數據庫c步驟:
1 連excel(自己知道其格式,最好是沒個字段在數據一一對應)
2 讀excel數據,填入到數據庫
我這里有個函數,實現把excel表格中數據導入數據庫,在一條數據導入前判斷數據庫中是否有該數據,如果有,就不再導入該數據(避免重復)
,你可以參考下


procedure TForm_qyxxcx.BitBtn2Click(Sender: TObject);
VAR
  I,J:INTEGER;
  col,row:integer;
  MsExcel,WBook,WSheet:OLEVARIANT;
  f_temp,strtemp:string;
begin
  if Main_form.lwt.Message_Confirm('為預防不可預測情況發生(字段太長、類型不一致等)'+#10#13+'強烈建議在導入前備份原來數據,'+#10#13+'確認:終止導入'+#10#13+'取消:繼續導入') then
    abort;

  cdsDJZY.Open;
  cdsDJZY.First;
  while not cdsDJZY.Eof do
    cdsDJZY.Delete;

  cdsDJZY.Close;
  cdsDJZY.Open;
  try
  begin
    MsExcel:= CreateOleObject('Excel.Application');
    WBook:=MsExcel.Application;
    if opendialog1.Execute then   //關聯到文件
    begin
     if opendialog1.FileName='' then
       abort;
      wbook.workbooks.Open(opendialog1.FileName);
    end;
    WBook.Visible:= true;
    WSheet:=WBook.worksheets[1];
  end
  except
  begin
    Application.Messagebox('您取消了操作或 Excel   沒有安裝!','ERROR!',   MB_ICONERROR   +   mb_Ok);
    Abort;
  end;
  end;

  row:=WSheet.UsedRange.Rows.Count;      //行
  col:=WSheet.UsedRange.columns.Count;     //列
  if (row=0) or (col = 0)  then
  begin
    showmessage('該excel文件沒有數據!請確認');
    abort;
  end;

  proform.Show;
  proform.ProgressBar1.Max:=row;

  with qqyb do
  begin
    open;
    for i:=1 to row-1 do    //要增加的行數
    begin   // 0 人員名稱  2 企業名稱
      //判斷是否存在該企業和人員,如果存在,不導入該記錄
      strtemp:='select * from qyb where qy_name = '''+WSheet.cells[i+1,1].Value+'''';
      Main_Form.lwt.DB_AdoQueryRun(qupdate,strtemp);
      if qupdate.RecordCount<>0 then   //  存在,加入臨時表  ,退出本次循環
      begin
        cdsDJZY.Append ;
        cdsDJZY.FieldByName('企業名稱').AsString := WSheet.cells[i+1,1].Value;
        cdsDJZY.Post;
        continue;
      end;
      Append; //不存在,繼續
      for j:=0 to col-1 do   //列
      begin
        proform.ProgressBar1.Position:=proform.ProgressBar1.Position+1;
//        if adory.Fields[j].FieldKind
        Fields[j].Value:= WSheet.cells[i+1,j+1].Value;
      end;
      Post;
    end;
  end;
  proform.ProgressBar1.Position:=0;
  proform.Hide;

  if cdsDJZY.RecordCount>1 then
  begin
    if Main_form.lwt.Message_Confirm('數據已經導入!,部分記錄因為已經存在,沒有導入,是否打印沒有導入記錄的請單?') then
    begin
      Main_form.lwt.DB_ShowReportByDataSet(cdsDJZY,'因為已經存在該企業導入失敗的信息');
      main_form.lwt.DB_Excel_Export(cdsdjzy,'c:\hello.xls');
    end;
  end
  else
  begin
    Main_Form.lwt.Message_Show('數據已經導入!');
  end;
  wbook.workbooks.close;
end;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM