如何实现批次将excel资料导入到sql,希望用delphi程序

解决方案 »

  1.   

    procedure TForm1.SpeedButton1Click(Sender: TObject);
    var
      i,j:integer;
      aa,bb:string;
      Myarray:array[1..100,1..2]of integer;begin
      if ListBox1.ItemIndex>0 then
        ListBox1.ItemIndex:=ListBox1.ItemIndex-1;
        label3.Caption:=inttostr(ListBox1.ItemIndex);
        //建立数据导入的联结关系,得到字段对应数组。
        //array〔i,1〕 记录目的字段;array〔i,2〕记录EXCEl中的列数。
        for i:=0 to listbox1.Items.Count-1 do begin
          myarray[i+1,1]:=i+1;
          for j:=1 to  ExcelWorksheet1.Cells.Columns.Count do begin
            aa:=ExcelWorksheet1.Cells.item[1,j];
            if trim(aa)='' then break;
            if listbox2.Items[i]=aa then
              myarray[i+1,2]:=j;
          end;
        end;    //数据导入
        i:=1;
        query1.Active:=true;
        query1.Edit;
        while trim(ExcelWorksheet1.Cells.item[i+1,1])<>'' do begin
          aa:=ExcelWorksheet1.Cells.item[i+1,1];
          if query1.Locate('ID',aa,[loCaseInsensitive])then begin
             query1.edit;
             for j:=1 to listbox1.Items.Count do begin
               if myarray[j,2]<>0 then
                 Query1.Fields[j-1].Value:=ExcelWorksheet1.Cells.item[i+1,myarray[j,2]];
             end;
           // showmessage('有重复记录。')
          end else begin
             query1.edit;
             query1.insert;
             for j:=1 to listbox1.Items.Count do begin
               if myarray[j,2]<>0 then
                 Query1.Fields[j-1].Value:=ExcelWorksheet1.Cells.item[i+1,myarray[j,2]];
             end;
          end;
          Label3.caption:=inttostr(i);
          i:=i+1;    end;
        query1.post;
        showmessage('共导入'+inttostr(i-1)+'条员工信息。');
    end;
      

  2.   

    [转载]在DELPHI中使用ADO直接访问Excel数据文件
    1.设置ADOConnection的ConnectionString
        构造ConnectionString时,OLE DB的提供者要选择Microsoft Jet 4.0 OLE DB Provider作为ADO的驱动程序。这本来是用于连接Access数据库的驱动程序,但也可打开Excel文件。
        连接的数据库名称当然就是你要打开的Excel文件,注意扩展名是*.xls,而不是*.mdb。
        最关键的一点是,还要设置扩展属性Extended Properties为“Excel 8.0”,否则,测试连接时会报告无法识别数据格式的错误。Extended Properties的属性值在“所有”参数页中输入。
        最后,设置完成后的ConnectionString中的各项参数为:
        Provider=Microsoft.Jet.OLEDB.4.0
        Data Source=MyExcelFile.xls
        Extended Properties=Excel 8.0
        Persist Security Info=False2.设置ADODataSet或ADOTable
        将ADODataSet或ADOTable连接到刚才的ADOConnection。如果不用ADOConnection,也可以参照上面的方法直接设置ADODataSet或ADOTable的ConnectionString属性。
        对于ADODataSet,需要将CommandType属性设置为cmdTableDirect,而对于ADOTable,则将TableDirect属性设置为True。因为,访问Excel文件是直接的数据文件访问,不是通过SQL语句来操作游标访问的。如果不设置直接访问,则系统会报告SQL语句格式错误等信息。
        然后,当你下拉ADODataSet中的CommandText属性或ADOTable的TableName属性时,就可以选择到要打开的工作表了。注意,表名后面多了加一个$符号。
              3.打开ADODataSet或ADOTable
    连上EXCEL了,具体操作就一样了。
      

  3.   

    對於zfmich()您的建議,当下拉ADODataSet中的CommandText属性或ADOTable的TableName属性时,會有提示需要user name & password,我需要如何做呢?
      

  4.   

    运行程序的时候,弹出以下提示:Excel已经被别的程序以独占的方式打开,那应该怎么办?