Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

954 lines
34 KiB

  1. # The documentation is at the __END__
  2. package Win32::OLE;
  3. use strict;
  4. use vars qw($VERSION @ISA @EXPORT @EXPORT_OK @EXPORT_FAIL $AUTOLOAD
  5. $CP $LCID $Warn $LastError $_NewEnum $_Unique);
  6. $VERSION = '0.1502';
  7. use Carp;
  8. use Exporter;
  9. use DynaLoader;
  10. @ISA = qw(Exporter DynaLoader);
  11. @EXPORT = qw();
  12. @EXPORT_OK = qw(in valof with HRESULT EVENTS OVERLOAD
  13. CP_ACP CP_OEMCP CP_MACCP CP_UTF7 CP_UTF8
  14. DISPATCH_METHOD DISPATCH_PROPERTYGET
  15. DISPATCH_PROPERTYPUT DISPATCH_PROPERTYPUTREF);
  16. @EXPORT_FAIL = qw(EVENTS OVERLOAD);
  17. sub export_fail {
  18. shift;
  19. my @unknown;
  20. while (@_) {
  21. my $symbol = shift;
  22. if ($symbol eq 'OVERLOAD') {
  23. eval <<'OVERLOAD';
  24. use overload '""' => \&valof,
  25. '0+' => \&valof,
  26. fallback => 1;
  27. OVERLOAD
  28. }
  29. elsif ($symbol eq 'EVENTS') {
  30. Win32::OLE->Initialize(Win32::OLE::COINIT_OLEINITIALIZE());
  31. }
  32. else {
  33. push @unknown, $symbol;
  34. }
  35. }
  36. return @unknown;
  37. }
  38. unless (defined &Dispatch) {
  39. # Use regular DynaLoader if XS part is not yet initialized
  40. bootstrap Win32::OLE;
  41. require Win32::OLE::Lite;
  42. }
  43. 1;
  44. ########################################################################
  45. __END__
  46. =head1 NAME
  47. Win32::OLE - OLE Automation extensions
  48. =head1 SYNOPSIS
  49. $ex = Win32::OLE->new('Excel.Application') or die "oops\n";
  50. $ex->Amethod("arg")->Bmethod->{'Property'} = "foo";
  51. $ex->Cmethod(undef,undef,$Arg3);
  52. $ex->Dmethod($RequiredArg1, {NamedArg1 => $Value1, NamedArg2 => $Value2});
  53. $wd = Win32::OLE->GetObject("D:\\Data\\Message.doc");
  54. $xl = Win32::OLE->GetActiveObject("Excel.Application");
  55. =head1 DESCRIPTION
  56. This module provides an interface to OLE Automation from Perl.
  57. OLE Automation brings VisualBasic like scripting capabilities and
  58. offers powerful extensibility and the ability to control many Win32
  59. applications from Perl scripts.
  60. The Win32::OLE module uses the IDispatch interface exclusively. It is
  61. not possible to access a custom OLE interface. OLE events and OCX's are
  62. currently not supported.
  63. Actually, that's no longer strictly true. This module now contains
  64. B<ALPHA> level support for OLE events. This is largely untested and the
  65. specific interface might still change in the future.
  66. =head2 Methods
  67. =over 8
  68. =item Win32::OLE->new(PROGID[, DESTRUCTOR])
  69. The new() class method starts a new instance of an OLE Automation object.
  70. It returns a reference to this object or C<undef> if the creation failed.
  71. The PROGID argument must be either the OLE I<program id> or the I<class id>
  72. of the required application. The optional DESTRUCTOR specifies a DESTROY-like
  73. method. This can be either a CODE reference or a string containing an OLE
  74. method name. It can be used to cleanly terminate OLE applications in case the
  75. Perl program dies.
  76. To create an object via DCOM on a remote server you can use an array
  77. reference in place of PROGID. The referenced array must contain the
  78. machine name and the I<program id> or I<class id>. For example:
  79. my $obj = Win32::OLE->new(['my.machine.com', 'Program.Id']);
  80. If the PROGID is a I<program id> then Win32::OLE will try to resolve the
  81. corresponding I<class id> locally. If the I<program id> is not registered
  82. locally then the remote registry is queried. This will only succeed if
  83. the local process has read access to the remote registry. The safest
  84. (and fastest) method is to specify the C<class id> directly.
  85. =item Win32::OLE->EnumAllObjects([CALLBACK])
  86. This class method returns the number Win32::OLE objects currently in
  87. existance. It will call the optional CALLBACK function for each of
  88. these objects:
  89. $Count = Win32::OLE->EnumAllObjects(sub {
  90. my $Object = shift;
  91. my $Class = Win32::OLE->QueryObjectType($Object);
  92. printf "# Object=%s Class=%s\n", $Object, $Class;
  93. });
  94. The EnumAllObjects() method is primarily a debugging tool. It can be
  95. used e.g. in an END block to check if all external connections have
  96. been properly destroyed.
  97. =item Win32::OLE->FreeUnusedLibraries()
  98. The FreeUnusedLibraries() class method unloads all unused OLE
  99. resources. These are the libraries of those classes of which all
  100. existing objects have been destroyed. The unloading of object
  101. libraries is really only important for long running processes that
  102. might instantiate a huge number of B<different> objects over time.
  103. Be aware that objects implemented in Visual Basic have a buggy
  104. implementation of this functionality: They pretend to be unloadable
  105. while they are actually still running their cleanup code. Unloading
  106. the DLL at that moment typically produces an access violation. The
  107. probability for this problem can be reduced by calling the
  108. SpinMessageLoop() method and sleep()ing for a few seconds.
  109. =item Win32::OLE->GetActiveObject(CLASS[, DESTRUCTOR])
  110. The GetActiveObject() class method returns an OLE reference to a
  111. running instance of the specified OLE automation server. It returns
  112. C<undef> if the server is not currently active. It will croak if
  113. the class is not even registered. The optional DESTRUCTOR method takes
  114. either a method name or a code reference. It is executed when the last
  115. reference to this object goes away. It is generally considered C<impolite>
  116. to stop applications that you did not start yourself.
  117. =item Win32::OLE->GetObject(MONIKER[, DESTRUCTOR])
  118. The GetObject() class method returns an OLE reference to the specified
  119. object. The object is specified by a pathname optionally followed by
  120. additional item subcomponent separated by exclamation marks '!'. The
  121. optional DESTRUCTOR argument has the same semantics as the DESTRUCTOR in
  122. new() or GetActiveObject().
  123. =item Win32::OLE->Initialize([COINIT])
  124. The Initialize() class method can be used to specify an alternative
  125. apartment model for the Perl thread. It must be called B<before> the
  126. first OLE object is created. If the C<Win32::OLE::Const> module is
  127. used then the call to the Initialize() method must be made from a BEGIN
  128. block before the first C<use> statement for the C<Win32::OLE::Const>
  129. module.
  130. Valid values for COINIT are:
  131. Win32::OLE::COINIT_APARTMENTTHREADED - single threaded
  132. Win32::OLE::COINIT_MULTITHREADED - the default
  133. Win32::OLE::COINIT_OLEINITIALIZE - single threaded, additional OLE stuff
  134. COINIT_OLEINITIALIZE is sometimes needed when an OLE object uses
  135. additional OLE compound document technologies not available from the
  136. normal COM subsystem (for example MAPI.Session seems to require it).
  137. Both COINIT_OLEINITIALIZE and COINIT_APARTMENTTHREADED create a hidden
  138. top level window and a message queue for the Perl process. This may
  139. create problems with other application, because Perl normally doesn't
  140. process its message queue. This means programs using synchronous
  141. communication between applications (such as DDE initiation), may hang
  142. until Perl makes another OLE method call/property access or terminates.
  143. This applies to InstallShield setups and many things started to shell
  144. associations. Please try to utilize the C<Win32::OLE-E<gt>SpinMessageLoop>
  145. and C<Win32::OLE-E<gt>Uninitialize> methods if you can not use the default
  146. COINIT_MULTITHREADED model.
  147. =item OBJECT->Invoke(METHOD[, ARGS])
  148. The Invoke() object method is an alternate way to invoke OLE
  149. methods. It is normally equivalent to C<$OBJECT->METHOD(@ARGS)>. This
  150. function must be used if the METHOD name contains characters not valid
  151. in a Perl variable name (like foreign language characters). It can
  152. also be used to invoke the default method of an object even if the
  153. default method has not been given a name in the type library. In this
  154. case use <undef> or C<''> as the method name. To invoke an OLE objects
  155. native Invoke() method (if such a thing exists), please use:
  156. $Object->Invoke('Invoke', @Args);
  157. =item Win32::OLE->LastError()
  158. The LastError() class method returns the last recorded OLE
  159. error. This is a dual value like the C<$!> variable: in a numeric
  160. context it returns the error number and in a string context it returns
  161. the error message. The error number is a signed HRESULT value. Please
  162. use the L<HRESULT(ERROR)> function to convert an unsigned hexadecimal
  163. constant to a signed HRESULT.
  164. The last OLE error is automatically reset by a successful OLE
  165. call. The numeric value can also explicitly be set by a call (which will
  166. discard the string value):
  167. Win32::OLE->LastError(0);
  168. =item OBJECT->LetProperty(NAME,ARGS,VALUE)
  169. In Win32::OLE property assignment using the hash syntax is equivalent
  170. to the Visual Basic C<Set> syntax (I<by reference> assignment):
  171. $Object->{Property} = $OtherObject;
  172. corresponds to this Visual Basic statement:
  173. Set Object.Property = OtherObject
  174. To get the I<by value> treatment of the Visual Basic C<Let> statement
  175. Object.Property = OtherObject
  176. you have to use the LetProperty() object method in Perl:
  177. $Object->LetProperty($Property, $OtherObject);
  178. LetProperty() also supports optional arguments for the property assignment.
  179. See L<OBJECT->SetProperty(NAME,ARGS,VALUE)> for details.
  180. =item Win32::OLE->MessageLoop()
  181. The MessageLoop() class method will run a standard Windows message
  182. loop, dispatching messages until the QuitMessageLoop() class method is
  183. called. It is used to wait for OLE events.
  184. =item Win32::OLE->Option(OPTION)
  185. The Option() class method can be used to inspect and modify
  186. L<Module Options>. The single argument form retrieves the value of
  187. an option:
  188. my $CP = Win32::OLE->Option('CP');
  189. A single call can be used to set multiple options simultaneously:
  190. Win32::OLE->Option(CP => CP_ACP, Warn => 3);
  191. =item Win32::OLE->QueryObjectType(OBJECT)
  192. The QueryObjectType() class method returns a list of the type library
  193. name and the objects class name. In a scalar context it returns the
  194. class name only. It returns C<undef> when the type information is not
  195. available.
  196. =item Win32::OLE->QuitMessageLoop()
  197. The QuitMessageLoop() class method posts a (user-level) "Quit" message
  198. to the current threads message loop. QuitMessageLoop() is typically
  199. called from an event handler. The MessageLoop() class method will
  200. return when it receives this "Quit" method.
  201. =item OBJECT->SetProperty(NAME,ARGS,VALUE)
  202. The SetProperty() method allows to modify properties with arguments,
  203. which is not supported by the hash syntax. The hash form
  204. $Object->{Property} = $Value;
  205. is equivalent to
  206. $Object->SetProperty('Property', $Value);
  207. Arguments must be specified between the property name and the new value:
  208. $Object->SetProperty('Property', @Args, $Value);
  209. It is not possible to use "named argument" syntax with this function
  210. because the new value must be the last argument to SetProperty().
  211. This method hides any native OLE object method called SetProperty().
  212. The native method will still be available through the Invoke() method:
  213. $Object->Invoke('SetProperty', @Args);
  214. =item Win32::OLE->SpinMessageLoop
  215. This class method retrieves all pending messages from the message queue
  216. and dispatches them to their respective window procedures. Calling this
  217. method is only necessary when not using the COINIT_MULTITHREADED model.
  218. All OLE method calls and property accesses automatically process the
  219. message queue.
  220. =item Win32::OLE->Uninitialize
  221. The Uninitialize() class method uninitializes the OLE subsystem. It
  222. also destroys the hidden top level window created by OLE for single
  223. threaded apartments. All OLE objects will become invalid after this call!
  224. It is possible to call the Initialize() class method again with a different
  225. apartment model after shutting down OLE with Uninitialize().
  226. =item Win32::OLE->WithEvents(OBJECT[, HANDLER[, INTERFACE]])
  227. This class method enables and disables the firing of events by the
  228. specified OBJECT. If no HANDLER is specified, then events are
  229. disconnected. For some objects Win32::OLE is not able to
  230. automatically determine the correct event interface. In this case the
  231. INTERFACE argument must contain either the COCLASS name of the OBJECT
  232. or the name of the event DISPATCH interface. Please read the L<Events>
  233. section below for detailed explanation of the Win32::OLE event
  234. support.
  235. =back
  236. Whenever Perl does not find a method name in the Win32::OLE package it
  237. is automatically used as the name of an OLE method and this method call
  238. is dispatched to the OLE server.
  239. There is one special hack built into the module: If a method or property
  240. name could not be resolved with the OLE object, then the default method
  241. of the object is called with the method name as its first parameter. So
  242. my $Sheet = $Worksheets->Table1;
  243. or
  244. my $Sheet = $Worksheets->{Table1};
  245. is resolved as
  246. my $Sheet = $Worksheet->Item('Table1');
  247. provided that the $Worksheets object doesnot have a C<Table1> method
  248. or property. This hack has been introduced to call the default method
  249. of collections which did not name the method in their type library. The
  250. recommended way to call the "unnamed" default method is:
  251. my $Sheet = $Worksheets->Invoke('', 'Table1');
  252. This special hack is disabled under C<use strict 'subs';>.
  253. =head2 Object methods and properties
  254. The object returned by the new() method can be used to invoke
  255. methods or retrieve properties in the same fashion as described
  256. in the documentation for the particular OLE class (eg. Microsoft
  257. Excel documentation describes the object hierarchy along with the
  258. properties and methods exposed for OLE access).
  259. Optional parameters on method calls can be omitted by using C<undef>
  260. as a placeholder. A better way is to use named arguments, as the
  261. order of optional parameters may change in later versions of the OLE
  262. server application. Named parameters can be specified in a reference
  263. to a hash as the last parameter to a method call.
  264. Properties can be retrieved or set using hash syntax, while methods
  265. can be invoked with the usual perl method call syntax. The C<keys>
  266. and C<each> functions can be used to enumerate an object's properties.
  267. Beware that a property is not always writable or even readable (sometimes
  268. raising exceptions when read while being undefined).
  269. If a method or property returns an embedded OLE object, method
  270. and property access can be chained as shown in the examples below.
  271. =head2 Functions
  272. The following functions are not exported by default.
  273. =over 8
  274. =item HRESULT(ERROR)
  275. The HRESULT() function converts an unsigned number into a signed HRESULT
  276. error value as used by OLE internally. This is necessary because Perl
  277. treats all hexadecimal constants as unsigned. To check if the last OLE
  278. function returned "Member not found" (0x80020003) you can write:
  279. if (Win32::OLE->LastError == HRESULT(0x80020003)) {
  280. # your error recovery here
  281. }
  282. =item in(COLLECTION)
  283. If COLLECTION is an OLE collection object then C<in $COLLECTION>
  284. returns a list of all members of the collection. This is a shortcut
  285. for C<Win32::OLE::Enum->All($COLLECTION)>. It is most commonly used in
  286. a C<foreach> loop:
  287. foreach my $value (in $collection) {
  288. # do something with $value here
  289. }
  290. =item valof(OBJECT)
  291. Normal assignment of Perl OLE objects creates just another reference
  292. to the OLE object. The valof() function explictly dereferences the
  293. object (through the default method) and returns the value of the object.
  294. my $RefOf = $Object;
  295. my $ValOf = valof $Object;
  296. $Object->{Value} = $NewValue;
  297. Now $ValOf still contains the old value wheras $RefOf would
  298. resolve to the $NewValue because it is still a reference to
  299. $Object.
  300. The valof() function can also be used to convert Win32::OLE::Variant
  301. objects to Perl values.
  302. =item with(OBJECT, PROPERTYNAME => VALUE, ...)
  303. This function provides a concise way to set the values of multiple
  304. properties of an object. It iterates over its arguments doing
  305. C<$OBJECT->{PROPERTYNAME} = $VALUE> on each trailing pair.
  306. =back
  307. =head2 Overloading
  308. The Win32::OLE objects can be overloaded to automatically convert to
  309. their values whenever they are used in a bool, numeric or string
  310. context. This is not enabled by default. You have to request it
  311. through the OVERLOAD pseudoexport:
  312. use Win32::OLE qw(in valof with OVERLOAD);
  313. You can still get the original string representation of an object
  314. (C<Win32::OLE=0xDEADBEEF>), e.g. for debugging, by using the
  315. C<overload::StrVal()> method:
  316. print overload::StrVal($object), "\n";
  317. Please note that C<OVERLOAD> is a global setting. If any module enables
  318. Win32::OLE overloading then it's active everywhere.
  319. =head2 Events
  320. The Win32::OLE module now contains B<ALPHA> level event support. This
  321. support is only available when Perl is running in a single threaded
  322. apartment. This can most easily be assured by using the C<EVENTS>
  323. pseudo-import:
  324. use Win32::OLE qw(EVENTS);
  325. which implicitly does something like:
  326. use Win32::OLE;
  327. Win32::OLE->Initialize(Win32::OLE::COINIT_OLEINITIALIZE);
  328. The current interface to OLE events should be considered experimental
  329. and is subject to change. It works as expected for normal OLE
  330. applications, but OLE control events often don't seem to work yet.
  331. Events must be enabled explicitly for an OLE object through the
  332. Win32::OLE->WithEvents() class method. The Win32::OLE module uses the
  333. IProvideClassInfo2 interface to determine the default event source of
  334. the object. If this interface is not supported, then the user must
  335. specify the name of the event source explicitly in the WithEvents()
  336. method call. It is also possible to specify the class name of the
  337. object as the third parameter. In this case Win32::OLE will try to
  338. look up the default source interface for this COCLASS.
  339. The HANDLER argument to Win32::OLE->WithEvents() can either be a CODE
  340. reference or a package name. In the first case, all events will invoke
  341. this particular function. The first two arguments to this function will
  342. be the OBJECT itself and the name of the event. The remaining arguments
  343. will be event specific.
  344. sub Event {
  345. my ($Obj,$Event,@Args) = @_;
  346. print "Event triggered: '$Event'\n";
  347. }
  348. Win32::OLE->WithEvents($Obj, \&Event);
  349. Alternatively the HANDLER argument can specify a package name. When the
  350. OBJECT fires an event, Win32::OLE will try to find a function of the same
  351. name as the event in this package. This function will be called with the
  352. OBJECT as the first argument followed again by the event specific parameters:
  353. package MyEvents;
  354. sub EventName1 {
  355. my ($Obj,@Args) = @_;
  356. print "EventName1 event triggered\n";
  357. }
  358. package main;
  359. Win32::OLE->WithEvents($Obj, 'MyEvents', 'IEventInterface');
  360. If Win32::OLE doesn't find a function with the name of the event then nothing
  361. happens.
  362. Event parameters passed I<by reference> are handled specially. They are not
  363. converted to the corresponding Perl datatype but passed as Win32::OLE::Variant
  364. objects. You can assign a new value to these objects with the help of the
  365. Put() method. This value will be passed back to the object when the event
  366. function returns:
  367. package MyEvents;
  368. sub BeforeClose {
  369. my ($self,$Cancel) = @_;
  370. $Cancel->Put(1) unless $MayClose;
  371. }
  372. Direct assignment to $Cancel would have no effect on the original value and
  373. would therefore not command the object to abort the closing action.
  374. =head2 Module Options
  375. The following module options can be accessed and modified with the
  376. C<Win32::OLE->Option> class method. In earlier versions of the Win32::OLE
  377. module these options were manipulated directly as class variables. This
  378. practice is now deprecated.
  379. =over 8
  380. =item CP
  381. This variable is used to determine the codepage used by all
  382. translations between Perl strings and Unicode strings used by the OLE
  383. interface. The default value is CP_ACP, which is the default ANSI
  384. codepage. Other possible values are CP_OEMCP, CP_MACCP, CP_UTF7 and
  385. CP_UTF8. These constants are not exported by default.
  386. =item LCID
  387. This variable controls the locale idnetifier used for all OLE calls.
  388. It is set to LOCALE_NEUTRAL by default. Please check the
  389. L<Win32::OLE::NLS> module for other locale related information.
  390. =item Warn
  391. This variable determines the behavior of the Win32::OLE module when
  392. an error happens. Valid values are:
  393. 0 Ignore error, return undef
  394. 1 Carp::carp if $^W is set (-w option)
  395. 2 always Carp::carp
  396. 3 Carp::croak
  397. The error number and message (without Carp line/module info) are
  398. available through the C<Win32::OLE->LastError> class method.
  399. Alternatively the Warn option can be set to a CODE reference. E.g.
  400. Win32::OLE->Option(Warn => 3);
  401. is equivalent to
  402. Win32::OLE->Option(Warn => \&Carp::croak);
  403. This can even be used to emulate the VisualBasic C<On Error Goto
  404. Label> construct:
  405. Win32::OLE->Option(Warn => sub {goto CheckError});
  406. # ... your normal OLE code here ...
  407. CheckError:
  408. # ... your error handling code here ...
  409. =item _NewEnum
  410. This option enables additional enumeration support for collection
  411. objects. When the C<_NewEnum> option is set, all collections will
  412. receive one additional property: C<_NewEnum>. The value of this
  413. property will be a reference to an array containing all the elements
  414. of the collection. This option can be useful when used in conjunction
  415. with an automatic tree traversal program, like C<Data::Dumper> or an
  416. object tree browser. The value of this option should be either 1
  417. (enabled) or 0 (disabled, default).
  418. Win32::OLE->Option(_NewEnum => 1);
  419. # ...
  420. my @sheets = @{$Excel->Worksheets->{_NewEnum}};
  421. In normal application code, this would be better written as:
  422. use Win32::OLE qw(in);
  423. # ...
  424. my @sheets = in $Excel->Worksheets;
  425. =item _Unique
  426. The C<_Unique> options guarantees that Win32::OLE will maintain a
  427. one-to-one mapping between Win32::OLE objects and the native COM/OLE
  428. objects. Without this option, you can query the same property twice
  429. and get two different Win32::OLE objects for the same underlying COM
  430. object.
  431. Using a unique proxy makes life easier for tree traversal algorithms
  432. to recognize they already visited a particular node. This option
  433. comes at a price: Win32::OLE has to maintain a global hash of all
  434. outstanding objects and their corresponding proxies. Identity checks
  435. on COM objects can also be expensive if the objects reside
  436. out-of-process or even on a different computer. Therefore this option
  437. is off by default unless the program is being run in the debugger.
  438. Unfortunately, this option doesn't always help. Some programs will
  439. return new COM objects for even the same property when asked for it
  440. multiple times (especially for collections). In this case, there is
  441. nothing Win32::OLE can do to detect that these objects are in fact
  442. identical (because they aren't at the COM level).
  443. The C<_Unique> option can be set to either 1 (enabled) or 0 (disabled,
  444. default).
  445. =back
  446. =head1 EXAMPLES
  447. Here is a simple Microsoft Excel application.
  448. use Win32::OLE;
  449. # use existing instance if Excel is already running
  450. eval {$ex = Win32::OLE->GetActiveObject('Excel.Application')};
  451. die "Excel not installed" if $@;
  452. unless (defined $ex) {
  453. $ex = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;})
  454. or die "Oops, cannot start Excel";
  455. }
  456. # get a new workbook
  457. $book = $ex->Workbooks->Add;
  458. # write to a particular cell
  459. $sheet = $book->Worksheets(1);
  460. $sheet->Cells(1,1)->{Value} = "foo";
  461. # write a 2 rows by 3 columns range
  462. $sheet->Range("A8:C9")->{Value} = [[ undef, 'Xyzzy', 'Plugh' ],
  463. [ 42, 'Perl', 3.1415 ]];
  464. # print "XyzzyPerl"
  465. $array = $sheet->Range("A8:C9")->{Value};
  466. for (@$array) {
  467. for (@$_) {
  468. print defined($_) ? "$_|" : "<undef>|";
  469. }
  470. print "\n";
  471. }
  472. # save and exit
  473. $book->SaveAs( 'test.xls' );
  474. undef $book;
  475. undef $ex;
  476. Please note the destructor specified on the Win32::OLE->new method. It ensures
  477. that Excel will shutdown properly even if the Perl program dies. Otherwise
  478. there could be a process leak if your application dies after having opened
  479. an OLE instance of Excel. It is the responsibility of the module user to
  480. make sure that all OLE objects are cleaned up properly!
  481. Here is an example of using Variant data types.
  482. use Win32::OLE;
  483. use Win32::OLE::Variant;
  484. $ex = Win32::OLE->new('Excel.Application', \&OleQuit) or die "oops\n";
  485. $ex->{Visible} = 1;
  486. $ex->Workbooks->Add;
  487. # should generate a warning under -w
  488. $ovR8 = Variant(VT_R8, "3 is a good number");
  489. $ex->Range("A1")->{Value} = $ovR8;
  490. $ex->Range("A2")->{Value} = Variant(VT_DATE, 'Jan 1,1970');
  491. sub OleQuit {
  492. my $self = shift;
  493. $self->Quit;
  494. }
  495. The above will put value "3" in cell A1 rather than the string
  496. "3 is a good number". Cell A2 will contain the date.
  497. Similarly, to invoke a method with some binary data, you can
  498. do the following:
  499. $obj->Method( Variant(VT_UI1, "foo\000b\001a\002r") );
  500. Here is a wrapper class that basically delegates everything but
  501. new() and DESTROY(). The wrapper class shown here is another way to
  502. properly shut down connections if your application is liable to die
  503. without proper cleanup. Your own wrappers will probably do something
  504. more specific to the particular OLE object you may be dealing with,
  505. like overriding the methods that you may wish to enhance with your
  506. own.
  507. package Excel;
  508. use Win32::OLE;
  509. sub new {
  510. my $s = {};
  511. if ($s->{Ex} = Win32::OLE->new('Excel.Application')) {
  512. return bless $s, shift;
  513. }
  514. return undef;
  515. }
  516. sub DESTROY {
  517. my $s = shift;
  518. if (exists $s->{Ex}) {
  519. print "# closing connection\n";
  520. $s->{Ex}->Quit;
  521. return undef;
  522. }
  523. }
  524. sub AUTOLOAD {
  525. my $s = shift;
  526. $AUTOLOAD =~ s/^.*:://;
  527. $s->{Ex}->$AUTOLOAD(@_);
  528. }
  529. 1;
  530. The above module can be used just like Win32::OLE, except that
  531. it takes care of closing connections in case of abnormal exits.
  532. Note that the effect of this specific example can be easier accomplished
  533. using the optional destructor argument of Win32::OLE::new:
  534. my $Excel = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;});
  535. Note that the delegation shown in the earlier example is not the same as
  536. true subclassing with respect to further inheritance of method calls in your
  537. specialized object. See L<perlobj>, L<perltoot> and L<perlbot> for details.
  538. True subclassing (available by setting C<@ISA>) is also feasible,
  539. as the following example demonstrates:
  540. #
  541. # Add error reporting to Win32::OLE
  542. #
  543. package Win32::OLE::Strict;
  544. use Carp;
  545. use Win32::OLE;
  546. use strict qw(vars);
  547. use vars qw($AUTOLOAD @ISA);
  548. @ISA = qw(Win32::OLE);
  549. sub AUTOLOAD {
  550. my $obj = shift;
  551. $AUTOLOAD =~ s/^.*:://;
  552. my $meth = $AUTOLOAD;
  553. $AUTOLOAD = "SUPER::" . $AUTOLOAD;
  554. my $retval = $obj->$AUTOLOAD(@_);
  555. unless (defined($retval) || $AUTOLOAD eq 'DESTROY') {
  556. my $err = Win32::OLE::LastError();
  557. croak(sprintf("$meth returned OLE error 0x%08x",$err))
  558. if $err;
  559. }
  560. return $retval;
  561. }
  562. 1;
  563. This package inherits the constructor new() from the Win32::OLE
  564. package. It is important to note that you cannot later rebless a
  565. Win32::OLE object as some information about the package is cached by
  566. the object. Always invoke the new() constructor through the right
  567. package!
  568. Here's how the above class will be used:
  569. use Win32::OLE::Strict;
  570. my $Excel = Win32::OLE::Strict->new('Excel.Application', 'Quit');
  571. my $Books = $Excel->Workbooks;
  572. $Books->UnknownMethod(42);
  573. In the sample above the call to UnknownMethod() will be caught with
  574. UnknownMethod returned OLE error 0x80020009 at test.pl line 5
  575. because the Workbooks object inherits the class C<Win32::OLE::Strict> from the
  576. C<$Excel> object.
  577. =head1 NOTES
  578. =head2 Hints for Microsoft Office automation
  579. =over 8
  580. =item Documentation
  581. The object model for the Office applications is defined in the Visual Basic
  582. reference guides for the various applications. These are typically not
  583. installed by default during the standard installation. They can be added
  584. later by rerunning the setup program with the custom install option.
  585. =item Class, Method and Property names
  586. The names have been changed between different versions of Office. For
  587. example C<Application> was a method in Office 95 and is a property in
  588. Office97. Therefore it will not show up in the list of property names
  589. C<keys %$object> when querying an Office 95 object.
  590. The class names are not always identical to the method/property names
  591. producing the object. E.g. the C<Workbook> method returns an object of
  592. type C<Workbook> in Office 95 and C<_Workbook> in Office 97.
  593. =item Moniker (GetObject support)
  594. Office applications seem to implement file monikers only. For example
  595. it seems to be impossible to retrieve a specific worksheet object through
  596. C<GetObject("File.XLS!Sheet")>. Furthermore, in Excel 95 the moniker starts
  597. a Worksheet object and in Excel 97 it returns a Workbook object. You can use
  598. either the Win32::OLE::QueryObjectType class method or the $object->{Version}
  599. property to write portable code.
  600. =item Enumeration of collection objects
  601. Enumerations seem to be incompletely implemented. Office 95 application don't
  602. seem to support neither the Reset() nor the Clone() methods. The Clone()
  603. method is still unimplemented in Office 97. A single walk through the
  604. collection similar to Visual Basics C<for each> construct does work however.
  605. =item Localization
  606. Starting with Office 97 Microsoft has changed the localized class, method and
  607. property names back into English. Note that string, date and currency
  608. arguments are still subject to locale specific interpretation. Perl uses the
  609. system default locale for all OLE transaction whereas Visual Basic uses a
  610. type library specific locale. A Visual Basic script would use "R1C1" in string
  611. arguments to specify relative references. A Perl script running on a German
  612. language Windows would have to use "Z1S1". Set the LCID module option
  613. to an English locale to write portable scripts. This variable should
  614. not be changed after creating the OLE objects; some methods seem to randomly
  615. fail if the locale is changed on the fly.
  616. =item SaveAs method in Word 97 doesn't work
  617. This is an known bug in Word 97. Search the MS knowledge base for Word /
  618. Foxpro incompatibility. That problem applies to the Perl OLE interface as
  619. well. A workaround is to use the WordBasic compatibility object. It doesn't
  620. support all the options of the native method though.
  621. $Word->WordBasic->FileSaveAs($file);
  622. The problem seems to be fixed by applying the Office 97 Service Release 1.
  623. =item Randomly failing method calls
  624. It seems like modifying objects that are not selected/activated is sometimes
  625. fragile. Most of these problems go away if the chart/sheet/document is
  626. selected or activated before being manipulated (just like an interactive
  627. user would automatically do it).
  628. =back
  629. =head2 Incompatibilities
  630. There are some incompatibilities with the version distributed by Activeware
  631. (as of build 306).
  632. =over 8
  633. =item 1
  634. The package name has changed from "OLE" to "Win32::OLE".
  635. =item 2
  636. All functions of the form "Win32::OLEFoo" are now "Win32::OLE::Foo",
  637. though the old names are temporarily accomodated. Win32::OLECreateObject()
  638. was changed to Win32::OLE::CreateObject(), and is now called
  639. Win32::OLE::new() bowing to established convention for naming constructors.
  640. The old names should be considered deprecated, and will be removed in the
  641. next version.
  642. =item 3
  643. Package "OLE::Variant" is now "Win32::OLE::Variant".
  644. =item 4
  645. The Variant function is new, and is exported by default. So are
  646. all the VT_XXX type constants.
  647. =item 5
  648. The support for collection objects has been moved into the package
  649. Win32::OLE::Enum. The C<keys %$object> method is now used to enumerate
  650. the properties of the object.
  651. =back
  652. =head2 Bugs and Limitations
  653. =over 8
  654. =item *
  655. To invoke a native OLE method with the same name as one of the
  656. Win32::OLE methods (C<Dispatch>, C<Invoke>, C<SetProperty>, C<DESTROY>,
  657. etc.), you have to use the C<Invoke> method:
  658. $Object->Invoke('Dispatch', @AdditionalArgs);
  659. The same is true for names exported by the Exporter or the Dynaloader
  660. modules, e.g.: C<export>, C<export_to_level>, C<import>,
  661. C<_push_tags>, C<export_tags>, C<export_ok_tags>, C<export_fail>,
  662. C<require_version>, C<dl_load_flags>,
  663. C<croak>, C<bootstrap>, C<dl_findfile>, C<dl_expandspec>,
  664. C<dl_find_symbol_anywhere>, C<dl_load_file>, C<dl_find_symbol>,
  665. C<dl_undef_symbols>, C<dl_install_xsub> and C<dl_error>.
  666. =back
  667. =head1 SEE ALSO
  668. The documentation for L<Win32::OLE::Const>, L<Win32::OLE::Enum>,
  669. L<Win32::OLE::NLS> and L<Win32::OLE::Variant> contains additional
  670. information about OLE support for Perl on Win32.
  671. =head1 AUTHORS
  672. Originally put together by the kind people at Hip and Activeware.
  673. Gurusamy Sarathy <[email protected]> subsequently fixed several
  674. major bugs, memory leaks, and reliability problems, along with some
  675. redesign of the code.
  676. Jan Dubois <[email protected]> pitched in with yet more massive redesign,
  677. added support for named parameters, and other significant enhancements.
  678. He's been hacking on it ever since.
  679. Please send questions about problems with this module to the
  680. Perl-Win32-Users mailinglist at ActiveState.com. The mailinglist charter
  681. requests that you put an [OLE] tag somewhere on the subject line (for OLE
  682. related questions only, of course).
  683. =head1 COPYRIGHT
  684. (c) 1995 Microsoft Corporation. All rights reserved.
  685. Developed by ActiveWare Internet Corp., now known as
  686. ActiveState Tool Corp., http://www.ActiveState.com
  687. Other modifications Copyright (c) 1997-2000 by Gurusamy Sarathy
  688. <[email protected]> and Jan Dubois <[email protected]>
  689. You may distribute under the terms of either the GNU General Public
  690. License or the Artistic License, as specified in the README file.
  691. =head1 VERSION
  692. Version 0.1502 7 September 2001
  693. =cut