Borland Delphi 7 TExcelApplication.Connect works o

2019-06-14 17:52发布

问题:

I'm in charge of maintaining some legacy code at my office (Pascal) due to it's limitations, I've written a delphi dll to access excel using TExcelApplication.

The dll works perfectly at the office, the machines are running Microsoft Office 2010, Windows 7 32-Bit and 64-Bit. The client is using Novel Workstations, Windows XP, Microsoft 2007.

The dll gives a breakpoint exception when encountering the TExcelApplication.Connect; command.

Other than the differences that I've mentioned, the scenario's are exactly the same.

Are there any limitations regarding accessing Microsoft Excel on a Novel Workstation, alternatively, is there a better way to access Excel documents?

Note: I just want to read from the Excel document, it spans multiple rows, columns and spreadsheets, the source Excel documents are *.xls 2007 documents.

It's primary function was to enable automated reconciliation against the Excel document.

Here is a snippet of the library code

library MyLibrary;
uses
  SysUtils, Classes, Variants, Dialogs, StdCtrls, OleServer, ExcelXP, Windows;
Type
  PString=String[254];

Var
  ExcelObj : TExcelApplication;

Procedure XLSOPEN(THENAME:PSTRING;VAR Reslt:PSTRING); stdcall;
Begin
  If FileExists(THENAME) Then
  Begin
    ExcelObj := TExcelApplication.Create(nil);
    ExcelObj.ConnectKind := ckRunningOrNew;
    ExcelObj.Connect;

    If ExcelObj=nil Then
    Begin
      Result := 'Error : EXCEL couldnt be started!';
      Exit;
    End Else
    Begin
      Result := 'Successful';
      Exit;
    End;
  End Else
  Begin
    Result := 'Error : File '+THENAME+' does not exist!';
    Exit;
  End;
End;

Exports XLSOPEN Name 'XLSOpen';

Begin
End.

回答1:

You need to add ActiveX to your uses list and use CoInitialize(nil); to initialize the ActiveX components. The reason for this is because Application->Initialize initializes the components, now that it's a dll, you have to manually initialize the component when it's loaded and use UnCoInitizlise; when unloading the dll.

USES ActiveX, Windows;

INITIALIZATION
  CoInitialize(nil);
FINALIZATION
  UnCoInitialize;