该excel文件中有两个字段,其一为数据库表的关键字段,另一字段为要修改的字段,可否实现在excel中修改过后的值,根据关键字段,更新到数据库表中。

解决方案 »

  1.   

    procedure TNewCardForm.Button1Click(Sender: TObject);
    var
        ExcelApp,MyWorkBook: OLEVariant;
        i,j,hykhlen,k,m,num: Integer;
        tmpName,
        tmpstr,
        newcardstr,
        tmphykh:String;begin
      num:=0;
      progbar.Max:=1100;
      progbar.Step:=1;
      progbar.Position:=0;
      if opendialog1.Execute then
      begin
        try
          ExcelApp:=CreateOleObject('Excel.Application');
          MyWorkBook:=CreateOleobject('Excel.Sheet');
        except
          application.Messagebox('无法打开Xls文件,请确认已 经安装EXCEL.','',
               mb_OK+mb_IconStop);
          Exit;
        end;
        MyworkBook:= ExcelApp.workBooks.Open(opendialog1.FileName);
        MyworkBook.Protect('',true);    //打开文件后,对文件进行操作
        for i:=2 to {11} 1100 do
        begin
          j:= MyWorkBook.WorkSheets[1].Cells[i,1].Value;
          try
            tmphykh:=inttostr(j);
          except
            showmessage('can not convert to string, error at the'+inttostr(i)+'line');
            exit;
          end;
          tmpName:= MyWorkBook.WorkSheets[1].Cells[i,2].Value;
          hykhlen:= Length(tmphykh);
          newcardstr:=  tmpHykh;
          if hykhlen<>0 then
          begin
            if hykhlen  <7 then
            begin
              k:=7-hykhlen;
              tmpstr:='';
              for m:=0 to k-1 do
                  tmpstr:=tmpstr+'0';
              newcardstr:=tmpstr+tmpHykh;
            end
            else if hykhlen  >7 then
            begin
              k:=hykhlen-7;
              newcardstr:=copy(tmphykh,k,7);
            end;
            //showmessage(newcardstr);
            with adoquery2 do
            begin
              close;
              SQL.Clear;
              SQL.Add('select id,hykh,[name] from customer where hykh=:hykhvalue');
              Parameters.ParamByName('hykhvalue').Value:= newcardstr;
              Open;
              prior;
              if not eof then
                if trim(tmpName)  = trim(FieldByName('Name').AsString) then
                begin
                  close;
                  SQL.Clear;
                  SQL.Add('update customer set newcard='''+newcardstr+''' where hykh=:hykhvalue');
                  Parameters.ParamByName('hykhvalue').Value:= newcardstr;
                  ExecSQL;
                  num:=num+1;
                end;
            end;
          end;
        end;
      end;
      showmessage('你一共更新了'+InttoStr(num)+'行数据!');
      ADOQuery1.Close;
      ADOQuery1.Open;
      ExcelApp.quit;
      ExcelApp:=Unassigned; //释放VARIANT变量
    end;