加载Excel电子表格的快速方法

加载Excel电子表格的快速方法,excel,delphi,delphi-xe3,Excel,Delphi,Delphi Xe3,我正在使用此代码加载只包含数字的excel电子表格。但是将整个文件加载到stringgrid中需要很长时间,有人知道更快的方法吗 procedure sh1(SheetIndex:integer); Var Xlapp1, Sheet:Variant ; MaxRow, MaxCol,X, Y:integer ; str:string; begin Str:=trim(form2.OpenDialog1.FileName); XLApp1 := createoleobject('excel.a

我正在使用此代码加载只包含数字的excel电子表格。但是将整个文件加载到
stringgrid
中需要很长时间,有人知道更快的方法吗

procedure sh1(SheetIndex:integer);
Var
Xlapp1, Sheet:Variant ;
MaxRow, MaxCol,X, Y:integer ;
str:string;
begin
Str:=trim(form2.OpenDialog1.FileName);

XLApp1 := createoleobject('excel.application');
XLApp1.Workbooks.open(Str) ;

Sheet := XLApp1.WorkSheets[SheetIndex] ;

MaxRow := Sheet.Usedrange.EntireRow.count ;
MaxCol := sheet.Usedrange.EntireColumn.count;

form2.stringgrid1.RowCount:=maxRow+1;
form2.StringGrid1.ColCount:=maxCol+1;
for x:=1 to maxCol do
     for y:=1 to maxRow do
            form2.stringgrid1.Cells[x,y]:=sheet.cells.item[y,x].value;

XLApp1.Workbooks.close;
end;

procedure TForm2.Button1Click(Sender: TObject);
begin
if opendialog1.Execute then begin
    stringgrid1.Visible:=true;
    sh1(1);
    end;
end;

您可以尝试将整个范围复制到变体数组。 差不多

procedure sh1(SheetIndex:integer);
Var
  Xlapp1, Sheet:Variant ;
  MaxRow, MaxCol,X, Y:integer ;
  str:string;
  arrData:Variant;
begin
  Str:=trim(form1.OpenDialog1.FileName);

  XLApp1 := createoleobject('excel.application');
  XLApp1.Workbooks.open(Str) ;

  Sheet := XLApp1.WorkSheets[SheetIndex] ;

  MaxRow := Sheet.Usedrange.EntireRow.count ;
  MaxCol := sheet.Usedrange.EntireColumn.count;

  //read the used range to a variant array
  arrData:= Sheet.UsedRange.Value;

  form1.stringgrid1.RowCount:=maxRow+1;
  form1.StringGrid1.ColCount:=maxCol+1;

  for x:=1 to maxCol do
    for y:=1 to maxRow do
      //copy data to grid
      form1.stringgrid1.Cells[x,y]:=arrData[y, x]; // do note that the indices are reversed (y, x)

  XLApp1.Workbooks.close;
end;

我用它来打开
.xlsx
,有没有一种不需要第三方组件的方法。因为在delphi上处理excel的“免费”组件似乎很少。但是有没有真正值得使用的组件?因为有了这个电子表格,我想处理很多事情,图表,算法等等。这似乎是另一个“我想要一个自由组件”的问题。你在问题中没有说你希望它是免费的。但是你在评论里是这样做的。解析.xlsx文件很棘手。你不会在一个简单的答案中得到代码。所以你肯定能像我们一样做好网络搜索。你的网络搜索结果出来了吗?无论如何,到目前为止,最简单的解决方案是修复你的COM代码,使其能够快速工作。不要每次都启动Excel的新实例。启动一次并重新使用。停止使用后期绑定,这会影响性能。不要一次只取出一个细胞。将整个范围拉出到变体阵列中。然后你的代码会飞起来。嗯,不是真的。事实上,我刚刚从另一个编写Excel的代码中复制了它。我会编辑代码的。谢谢丹尼尔,现在很快。谢谢:这是一个很棒的代码。我还建议在单元格中处理excel的错误(否则会得到AV):
v:Variant;v:=arrData[y,x];如果变量错误(v),则grid.Cells[x,y]:='error'否则grid.Cells[x,y]:=v