使用了3个控件:table1,button1,opendialog1
在这里,我把所有判断都去掉了,为的是让大家更快的阅读procedure TForm_testin.Button1Click(Sender: TObject);
var
   v:variant;
   j,k:integer;
begin
  if opendialog1.Execute then
    begin
      v:=createoleobject('Excel.Application');//创建OLE对象
      v.workbooks.open(opendialog1.FileName);//打开导入文件
      k:=v.workbooks[1].sheets[1].cells.count;//统计导入文件的行数(*******估计是这里出了问题*******)
      table1.Open;
        for j:=1 to k do
          begin
            table1.Append;
            //数据库的字段1-10,13类型均为文本,10-11类型为时间,字段1为主键
            table1.Fields.Fields[0].AsString:=v.workbooks[1].sheets[1].cells[j,1];
            table1.Fields.Fields[1].asstring:=v.workbooks[1].sheets[1].cells[j,2];
            table1.Fields.Fields[2].asstring:=v.workbooks[1].sheets[1].cells[j,3];
            table1.Fields.Fields[3].asstring:=v.workbooks[1].sheets[1].cells[j,4];
            table1.Fields.Fields[4].asstring:=v.workbooks[1].sheets[1].cells[j,5];
            table1.Fields.Fields[5].asstring:=v.workbooks[1].sheets[1].cells[j,6];
            table1.Fields.Fields[6].asstring:=v.workbooks[1].sheets[1].cells[j,7];
            table1.Fields.Fields[7].asstring:=v.workbooks[1].sheets[1].cells[j,8];
            table1.Fields.Fields[8].asstring:=v.workbooks[1].sheets[1].cells[j,9];
            table1.Fields.Fields[9].asstring:=v.workbooks[1].sheets[1].cells[j,10];
            table1.Fields.Fields[10].AsDateTime:=now;
            table1.Fields.Fields[11].AsDateTime:=now;
            table1.Fields.Fields[12].asstring:=v.workbooks[1].sheets[1].cells[j,13];
            table1.Next;
          end;
      table1.post;
      table1.Close;
    end;
end;
运行的结果是:最后运行会报错,大概意思是"关键字即字段1不能为空!";,但是数据导入正常.我想肯定是k:=v.workbooks[1].sheets[1].cells.count这条语句出问题了!但我又不知道如何对Excel中的有效行数进行统计.大侠帮帮我啦!

解决方案 »

  1.   

    你将k 尽可能的设大点,比如k=100000,然后在循环中判断结束的时候跳出如:
    if v.workbooks[1].sheets[1].cells[j,1]='' then
    break;
      

  2.   

    上面的cells[j,1]中的1,你改为你那个关键字段对应的列号.
      

  3.   

    回复人: xhh_88(三友) ( ) 信誉:105  2004-11-02 21:53:00  得分: 0  
     
     
       你将k 尽可能的设大点,比如k=100000,然后在循环中判断结束的时候跳出如:
    if v.workbooks[1].sheets[1].cells[j,1]='' then
    break;
      
     
    ******************************************************************
    if trim(v.workbooks[1].sheets[1].cells[j,1])='' then
    break;
    就可以了,谢谢你拉!给分拉!