Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to load Excel spreadsheet [closed]

I'm using this code to load an excel spreadsheet containing only numbers. But it takes too long to load the whole file into a stringgrid, anyone know a faster way to do this?

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;
like image 284
Ammadeux Avatar asked Feb 12 '13 11:02

Ammadeux


People also ask

Why does it take so long for Excel to close?

You may need to repair Office, or there may be a hidden workbook starting up with the application that is taking a long time to close. Click View>Unhide to see if anything is there. My second option for you is to try running it in a safe mode. Then kindly try to uninstall and reinstall it.

Can you pull data from a closed Excel file?

Extracting data from a closed file in another workbook is a common request by most of the excel user. They would like to pull or consolidate data from closed files; however, this is not possible.

How do I unfreeze Excel without losing work?

When Excel apps opens, you may also click File>Info>Manage Workbook>Recover Unsaved Workbooks, see if you could find your workbook. If you find it, select it and click Open and save it again.


1 Answers

You can try to copy the whole range to a variant array. Something like

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;
like image 108
Daniel Avatar answered Nov 01 '22 11:11

Daniel