一个excel文件,里面从第4行开始有数据,有6列数据,第2列是日期型"24-Feb-04"
有多少行数据不确认,是动态的.请问如何从这个文件中读出记录.

解决方案 »

  1.   

    下边函数返回一个记录集,这个记录集中包含的就是从excel中读入的数据
    Function ExcelToADOQuery: TADOQuery;
    var
      eclApp,WorkBook:Variant;
      tempOpenDialog: TOpenDialog;
      tempADOQuery:TADOQuery;
      sFileName:string;
      sSheetName:string;
      i:integer;
    begin
      Result:=nil;
      tempOpenDialog:=TOpenDialog.Create(nil);
      tempOpenDialog.Filter:='Excel文件格式(*.xls)|*.xls';
      if tempOpenDialog.Execute then
        begin
          sFileName:=tempOpenDialog.FileName;
          If tempADOQuery<>nil Then tempADOQuery.Free;
          tempADOQuery:=TADOQuery.Create(nil);
          try
          if VarIsEmpty(eclApp) then
            eclApp:=CreateOleObject('Excel.Application');
          WorkBook:=eclApp.Workbooks.Open(sFileName);
          Except on e: exception do
            begin
              MessageBox(Application.handle,PChar('导入过程中发生错误!'+#13+'错误信息:'#10 + e.message),'错误',MB_OK+MB_ICONERROR);
              Exit;
            end;
          end;
          sSheetName:=Workbook.Sheets[1].Name;      WorkBook.saved:=true;
          WorkBook.close;
          eclApp.Quit;
          WorkBook := Unassigned;
          eclApp := Unassigned;
          try
            with tempADOQuery do
            begin
              ConnectionString:='Provider = Microsoft.Jet.OLEDB.4.0;Data Source='+sFileName+';Extended Properties=Excel 8.0;';
              SQL.Clear;
              SQL.Add('select * from ['+sSheetName+'$]');
              Open;
            end;
            For i:=0 To tempADOQuery.Fields.Count-1 Do
              tempADOQuery.Fields.Fields[i].DisplayWidth :=10;
          except  on e: exception do
            begin
              MessageBox(Application.handle,PChar('导入过程中发生错误!'+#13+'错误信息:'#10 + e.message),'错误',MB_OK+MB_ICONERROR);
              Abort;
            end;
          end;
        end;
      Result:=tempADOQuery;
      tempOpenDialog.Free;end;
      

  2.   

    按上面说的,可以实现导入,但对于excel不知道多少行的话,还真没法控制循环多少次。我也想过这个问题,一直没有好招!
      

  3.   

    Excel 的 Worksheet 对象有一个UsedRange 属性 返回一个 Range 对象,此对象代表指定工作表中的已用区域。  行数= UsedRange.Row + UsedRange.Rows.Count-1
      

  4.   

    如何知道Excel中有多少行纪录呢?