Thursday, February 15, 2018

DELPHI - How to open Excel with .xls/.xlsx file

In sFile variable is saved path to opened file.
var
  sFile : string;
  pExcel : TExcelApplication;
begin
  ...
  iLocaleID := GetUserDefaultLCID;

  pExcel := TExcelApplication.Create( nil );                  
  pExcel.DisplayAlerts[ iLocaleID ] := false;
  pExcel.Connect;
  pExcel.Visible[ iLocaleID ] := true;

  pExcel.Workbooks.Open( sFile,
                         EmptyParam, EmptyParam, EmptyParam,
                         EmptyParam, EmptyParam, EmptyParam, EmptyParam,
                         EmptyParam, EmptyParam, EmptyParam, EmptyParam,
                         EmptyParam, EmptyParam, EmptyParam, iLocaleID );
In old Delphi (6) I used directed opening through COM, something like this:
uses ComObj;

const
  cExcelIdentifier = 'excel.application';

{ ---------------------------------------------------------------------------
  Try to run it.
  --------------------------------------------------------------------------- }
function TExcel.Execute : boolean;
begin
  result := false;

  FExcel := CreateOleObject( cExcelIdentifier );

  if VarIsEmpty( FExcel ) then
    begin
      MessageDlg( 'Application is not accessible.', mtError,  [mbOk], 0 );
      exit;
    end;

  FExcel.Visible := true;
  FExcel.Workbooks.Add( 1 );

  result := true;
end;

No comments:

Post a Comment