Pages

Friday, October 28, 2011

Delphi read data from excel

This procedure will access and read data from excel files (*.xls and *.xls). Here is the code :
procedure Alert_Xls(AXLSFile: string);
const
  xlCellTypeLastCell = $0000000B;
var
  XLApp, Sheet: OLEVariant;
  RangeMatrix: Variant;
  x, y, k, r: Integer;
begin  
  XLApp := CreateOleObject('Excel.Application');
  try
    XLApp.Visible := False;
    XLApp.Workbooks.Open(AXLSFile);
    Sheet := XLApp.Workbooks[ExtractFileName(AXLSFile)].WorkSheets[1];
    Sheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate;
    x := XLApp.ActiveCell.Row;
    y := XLApp.ActiveCell.Column;

    RangeMatrix := XLApp.Range['A1', XLApp.Cells.Item[X, Y]].Value;

    k := 1;
    repeat
      for r := 1 to y do
        //this section to operate data, change as your need
        ShowMessage(RangeMatrix[K, R]);
      Inc(k, 1);      
    until k > x;

    RangeMatrix := Unassigned;

  finally
    if not VarIsEmpty(XLApp) then
    begin
      XLApp.Quit;
      XLAPP := Unassigned;
      Sheet := Unassigned;      
    end;
  end;
end;

No comments:

Post a Comment

Don't Forget To Join Our Community
×
Widget