home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _4ec6219e78bcda2dddcc112a299c1794 < prev    next >
Text File  |  2004-06-01  |  22KB  |  441 lines

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2.  
  3. <html>
  4.  
  5. <head>
  6. <title>ActivePerl FAQ - Using OLE with Perl</title>
  7. <link rel="STYLESHEET" href="../../Active.css" type="text/css" media="screen">
  8. </head>
  9.  
  10. <body>
  11.  
  12. <table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#EAE2BB">
  13. <tr> 
  14. <td width="57"><a target=_blank href="http://www.ActiveState.com/ActivePerl/">
  15. <img src="../../images/activeperl_logo.gif" width="57" height="48" border="0" alt="ActivePerl"></a></td>
  16. <td><div align="center" class="heading">ActivePerl User Guide</div></td>
  17. <td width="112"><a target=_blank  href="http://www.ActiveState.com">
  18. <img src="../../images/AS_logo.gif" width="112" height="48" border="0"  alt="ActiveState" /></a></td>
  19. </tr>
  20. <tr>
  21. <td class="lineColour" colspan="3"></td>
  22. </tr>
  23. </table>
  24.  
  25. <h1>Using OLE with Perl</h1>
  26.  
  27. <ul>
  28.   <li><a class="doc" href="#NAME">NAME</a>
  29.   <li><a class="doc" href="#DESCRIPTION">DESCRIPTION</a>
  30.     <ul>
  31.       <li><a class="doc" href="#use_ole">Can I use OLE with Perl?</a>
  32.       <li><a class="doc" href="#changed_by_4xx">What has changed with OLE since build 3xx</a>
  33.       <li><a class="doc" href="#print_word">How do I print a Microsoft Word document?</a>
  34.       <li><a class="doc" href="#extract_cells">How do I extract a series of cells from
  35.         Microsoft Excel?</a>
  36.       <li><a class="doc" href="#make_chart">How do I make a chart in Microsoft Excel?</a>
  37.       <li><a class="doc" href="#save_chart">How do I save a chart from Microsoft Excel as
  38.         GIF/JPEG/PNG?</a>
  39.       <li><a class="doc" href="#run_macro">How do I run a macro in Microsoft Excel?</a>
  40.       <li><a class="doc" href="#set_name_cell">How do I set the name of a cell in Microsoft
  41.         Excel?</a>
  42.       <li><a class="doc" href="#create_new_folder">How do I create a new folder in Outlook?</a>
  43.       <li><a class="doc" href="#use_ado">How do I use ADO?</a>
  44.       <li><a class="doc" href="#use_notes">How do I use Lotus Notes?</a>
  45.       <li><a class="doc" href="#set_printer">How do I set the printer?</a>
  46.       <li><a class="doc" href="#convert_vba">How do I convert a VBA macro to Perl?</a>
  47.       <li><a class="doc" href="#find_docs">Where do I find documentation for the object
  48.         models?</a>
  49.       <li><a class="doc" href="#find_constants">OK, but can I at least find the constants
  50.         that are exported from Win32::OLE::Const?</a>
  51.       <li><a class="doc" href="#errors">Why doesn't $! get set with the error message I am
  52.         generating?</a>
  53.       <li><a class="doc" href="#odbc_ole">Why do I get an error when using ODBC and OLE?</a>
  54.       <li><a class="doc" href="#strict">Why doesn't it work - even after all this?</a>
  55.     </ul>
  56.   <li><a class="doc" href="#AUTHOR_AND_COPYRIGHT">AUTHOR AND COPYRIGHT</a>
  57. </ul>
  58.  
  59. <h2><a name="NAME">NAME</a></h2>
  60. <p>ActivePerl-faq12 - Using OLE with Perl</p>
  61.  
  62. <h2><a name="DESCRIPTION">DESCRIPTION</a></h2>
  63. <p>How to use OLE automation with Perl - through the Win32::OLE module</p>
  64.  
  65. <h2><a name="use_ole">Can I use OLE with Perl?</a></h2>
  66. <p>Yes - otherwise this FAQ wouldn't have been a separate FAQ. ;-)</p>
  67. <p>If you want to use OLE with Perl you need the Win32::OLE module. And you need
  68. to read the documentation that comes with it.</p>
  69. <p><code>use Win32::OLE</code> doesn't export any variables and functions to the
  70. main namespace, so if you want easy access to the <code>in</code> and <code>with</code>
  71. functions you should load the module with</p>
  72. <blockquote>
  73.   <p><code>use Win32::OLE qw(in with);</code></p>
  74. </blockquote>
  75.  
  76. <h2><a name="changed_by_4xx">What has changed with OLE since build 3xx</a></h2>
  77. <p>A lot - Gurusamy Sarathy and then Jan Dubois redesigned the code and added a
  78. bundle of enhancements. Old scripts should run with little or no modifications.
  79. When writing new scripts there is no excuse for not using the new Win32::OLE
  80. module options.</p>
  81. <p>Look at the Win::OLE module documentation (under Incompatibilities) and in
  82. particular the <a class="doc" href="release-old.html#Whats_Changed">'What's changed from
  83. 300 series builds'</a> in the release notes.</p>
  84.  
  85. <h2><a name="print_word">How do I print a Microsoft Word document?</a></h2>
  86. <p>Use the method PrintOut on a document object, for example:</p>
  87. <blockquote>
  88.   <p><code>use strict;<br>
  89.   use Win32::OLE;<br>
  90.   use Win32::OLE::Const 'Microsoft Word';<br>
  91.   <br>
  92.   my $Word = Win32::OLE->new('Word.Application', 'Quit');<br>
  93.   # $Word->{'Visible'} = 1;         #
  94.   if you want to see what's going on<br>
  95.   $Word->Documents->Open("C:\\DOCUMENTS\\test.doc")<br>
  96.       || die("Unable to open document ",
  97.   Win32::OLE->LastError());<br>
  98.   $Word->ActiveDocument->PrintOut({<br>
  99.       Background => 0,<br>
  100.       Append     => 0,<br>
  101.       Range      =>
  102.   wdPrintAllDocument,<br>
  103.       Item       =>
  104.   wdPrintDocumentContent,<br>
  105.       Copies     => 1,<br>
  106.       PageType   => wdPrintAllPages,<br>
  107.   });</code></p>
  108. </blockquote>
  109. <p>or simply</p>
  110. <blockquote>
  111.   <p><code>$Word->ActiveDocument->PrintOut;</code></p>
  112. </blockquote>
  113.  
  114. <h2><a name="extract_cells">How do I extract a series of cells from Microsoft Excel?</a></h2>
  115. <p>If you have a sheet object you can extract the values of a series of cells
  116. through $Sheet->Range->{'Value'}, for example:</p>
  117. <blockquote>
  118.   <p><code>my $array = $Sheet->Range("A8:B9")->{'Value'};</code></p>
  119. </blockquote>
  120. <p>Now $array[0][0] contains the value of cell A8, $array[0][1] the value of
  121. cell B8, $array[1][0] the value of cell A9 and $array[1][1] the value of cell
  122. B9.</p>
  123. <p>What is returned is an two-dimensional array (OK, an array with references to
  124. arrays) that contains the values of the requested cells.</p>
  125. <p>A complete example is here:</p>
  126. <blockquote>
  127.   <code>use strict;<br>
  128.   use Win32::OLE qw(in with);<br>
  129.   use Win32::OLE::Const 'Microsoft Excel';<br>
  130.   $Win32::OLE::Warn = 3;                                #
  131.   die on errors...<br>
  132.   my $Excel = Win32::OLE->GetActiveObject('Excel.Application')<br>
  133.       || Win32::OLE->new('Excel.Application', 'Quit');  #
  134.   get already active Excel<br>
  135.                                                         #
  136.   application or open new<br>
  137.   my $Book = $Excel->Workbooks->Open("C:\\DOCUMENTS\\test.xls"); #
  138.   open Excel file<br>
  139.   my $Sheet = $Book->Worksheets(1);                     #
  140.   select worksheet number 1<br>
  141.   my $array = $Sheet->Range("A8:B9")->{'Value'};        #
  142.   get the contents<br>
  143.   $Book->Close;<br>
  144.   foreach my $ref_array (@$array) {                     #
  145.   loop through the array<br>
  146.                                                         #
  147.   referenced by $array<br>
  148.       foreach my $scalar (@$ref_array) {<br>
  149.           print "$scalar\t";<br>
  150.       }<br>
  151.       print "\n";<br>
  152.   }</code>
  153. </blockquote>
  154. <p>To retrieve the formatted value of a cell you should use the <code>{'Text'}</code>
  155. property instead of the <code>{'Value'}</code> property. This returns exactly
  156. what is being displayed on the screen though! If the column is not wide enough,
  157. you get a value of '######':</p>
  158. <blockquote>
  159.   <p><code>my $array = $Sheet->Range("A8:B9")->{'Text'};</code></p>
  160. </blockquote>
  161.  
  162. <h2><a name="make_chart">How do I make a chart in Microsoft Excel?</a></h2>
  163. <p>A good idea would be to record a macro in Microsoft Excel and then <a class="doc" href="#convert_vba">convert
  164. it to Perl</a>. But here is a complete example:</p>
  165. <blockquote>
  166.   <p><code>use strict;<br>
  167.   use Win32::OLE;<br>
  168.   use Win32::OLE::Const 'Microsoft Excel';<br>
  169.   <br>
  170.   my $Excel = Win32::OLE->new("Excel.Application");<br>
  171.   $Excel->{Visible} = 1;<br>
  172.   <br>
  173.   my $Book = $Excel->Workbooks->Add;<br>
  174.   my $Sheet = $Book->Worksheets(1);<br>
  175.   my $Range = $Sheet->Range("A2:C7");<br>
  176.   $Range->{Value} =<br>
  177.       [['Delivered', 'En route', 'To be shipped'],<br>
  178.        [504, 102, 86],<br>
  179.        [670, 150, 174],<br>
  180.        [891, 261, 201],<br>
  181.        [1274, 471, 321],<br>
  182.        [1563, 536, 241]];<br>
  183.   <br>
  184.   my $Chart = $Excel->Charts->Add;<br>
  185.   $Chart->{ChartType} = xlAreaStacked;<br>
  186.   $Chart->SetSourceData({Source => $Range, PlotBy => xlColumns});<br>
  187.   $Chart->{HasTitle} = 1;<br>
  188.   $Chart->ChartTitle->{Text} = "Items delivered, en route and to be
  189.   shipped";</code></p>
  190. </blockquote>
  191.  
  192.  
  193. <h2><a name="save_chart">How do I save a chart from Microsoft Excel as GIF/JPEG/PNG?</a></h2>
  194. <p>You can use the Export method of a chart. If you have a chartobject the code
  195. looks like this</p>
  196. <blockquote>
  197.   <p><code>$ChartObj->Chart->Export({<br>
  198.       FileName    =>
  199.   "$graphics_filename",<br>
  200.       FilterName  => 'GIF',<br>
  201.       Interactive => 0});</code></p>
  202. </blockquote>
  203. <p>A complete example that opens an Excel workbook, loops through all the charts
  204. and saves them as GIFs and then closes the Excel workbook is here:</p>
  205. <blockquote>
  206.   <p><code>use strict;<br>
  207.   use Win32::OLE qw(in with);<br>
  208.   use Win32::OLE::Const;<br>
  209.   use Win32::OLE::Const 'Microsoft Excel';<br>
  210.   $Win32::OLE::Warn = 3;        # die on
  211.   errors...<br>
  212.   <br>
  213.   my $filename = 'c:\\documents\\test.xls';<br>
  214.   my $filter = 'GIF';           #
  215.   can be GIF, JPG, JPEG or PNG<br>
  216.   my $count = 0;<br>
  217.   <br>
  218.   my $Excel = Win32::OLE->GetActiveObject('Excel.Application')<br>
  219.       || Win32::OLE->new('Excel.Application', 'Quit');  #
  220.   use the Excel application if it's open, otherwise open new<br>
  221.   my $Book = $Excel->Workbooks->Open( $filename );      #
  222.   open the file<br>
  223.   foreach my $Sheet (in $Book->Sheets) {                #
  224.   loop through all sheets<br>
  225.       foreach my $ChartObj (in $Sheet->ChartObjects) {  #
  226.   loop through all chartobjects in the sheet<br>
  227.           my $savename =
  228.   "$filename." . $count++ . ".$filter";<br>
  229.           $ChartObj->Chart->Export({<br>
  230.               FileName    =>
  231.   $savename,<br>
  232.               FilterName  =>
  233.   $filter,<br>
  234.               Interactive =>
  235.   0});<br>
  236.       }<br>
  237.   }<br>
  238.   $Book->Close;</code></p>
  239. </blockquote>
  240.  
  241. <h2><a name="run_macro">How do I run a macro in Microsoft Excel?</a></h2>
  242. <p>Macros in Microsoft Excel can be run by using the $Excel->Run method, for
  243. example:</p>
  244. <blockquote>
  245.   <p><code>$Excel->Run("PrintPDFFile");</code></p>
  246. </blockquote>
  247. <p>In order to do this, you of course need to have a macro in Excel that's
  248. called 'PrintPDFFile'...</p>
  249.  
  250.  
  251. <h2><a name="set_name_cell">How do I set the name of a cell in Microsoft Excel?</a></h2>
  252. <p>Use the Names->Add method on a sheet, giving it a name and a range object
  253. to apply the name to, for example:</p>
  254. <blockquote>
  255.   <p><code>$Sheet->Names->Add({Name => 'NetCost', RefersTo =>
  256.   $Sheet->Range('$B$10')});</code></p>
  257. </blockquote>
  258.  
  259. <h2><a name="create_new_folder">How do I create a new folder in Outlook?</a></h2>
  260. <p>Again, an example :-)</p>
  261. <blockquote>
  262.   <p><code>use strict;<br>
  263.   use Win32::OLE;<br>
  264.   use Win32::OLE::Const 'Microsoft Outlook';<br>
  265.   <br>
  266.   my $Outlook = Win32::OLE->new('Outlook.Application', 'Quit');<br>
  267.   my $ol = Win32::OLE::Const->Load($Outlook);<br>
  268.   <br>
  269.   my $namespace = $Outlook->GetNamespace("MAPI");<br>
  270.   my $Folder = $namespace->GetDefaultFolder(olFolderInbox);<br>
  271.   my $NewFolder = $Folder->Folders->Add("Test1");</code></p>
  272. </blockquote>
  273.  
  274. <h2><a name="use_ado">How do I use ADO?</a></h2>
  275. <p>In order to use ActiveX Data Objects (ADO) you can just</p>
  276. <blockquote>
  277.   <p><code>use strict;<br>
  278.   use Win32::OLE;<br>
  279.   use Win32::OLE::Const 'Microsoft ActiveX Data Objects';<br>
  280.   my $Conn = Win32::OLE->new('ADODB.Connection'); # creates a connection
  281.   object<br>
  282.   my $RS = Win32::OLE->new('ADODB.Recordset');    #
  283.   creates a recordset object<br>
  284.   $Conn->Open('DBname');                          #
  285.   opens the database connection<br>
  286.   <br>
  287.   my $Fields = ['Id', 'Name', 'Phone'];<br>
  288.   my $Values = [1, 'Joe Doe', '555-1234'];<br>
  289.   $RS->AddNew($Fields, $Values);                  #
  290.   adds a record<br>
  291.   <br>
  292.   print "This didn't go well: ", Win32::OLE->LastError(),
  293.   "\n";<br>
  294.       if (Win32::OLE->LastError());<br>
  295.   <br>
  296.   $RS->Close;<br>
  297.   $Conn->Close;</code></p>
  298. </blockquote>
  299. <p>To get further than this you should have a look at the ADO FAQ at 
  300. <a class="doc" href="http://www.fastnetltd.ndirect.co.uk/Perl/perl-win32-database.html">http://www.fastnetltd.ndirect.co.uk/Perl/perl-win32-database.html</a>
  301. or Jan Dubois article in TPJ#10 (visit The Perl Journal at <a class="doc" href="http://tpj.com/">http://tpj.com/</a>).</p>
  302.  
  303.  
  304. <h2><a name="use_notes">How do I use Lotus Notes?</a></h2>
  305. <p>Lotus Notes can be accessed through OLE, for example like this:</p>
  306. <blockquote>
  307.   <p><code>use strict;<br>
  308.   use Win32::OLE;<br>
  309.   my $Notes = Win32::OLE->new('Notes.NotesSession')<br>
  310.       or die "Cannot start Lotus Notes Session
  311.   object.\n";<br>
  312.   my ($Version) = ($Notes->{NotesVersion} =~ /\s*(.*\S)\s*$/);<br>
  313.   print "The current user is $Notes->{UserName}.\n";<br>
  314.   print "Running Notes \"$Version\" on
  315.   \"$Notes->{Platform}\".\n";<br>
  316.   my $Database = $Notes->GetDatabase('', 'help4.nsf');<br>
  317.   my $AllDocuments = $Database->AllDocuments;<br>
  318.   my $Count = $AllDocuments->Count;<br>
  319.   print "There are $Count documents in the database.\n";<br>
  320.   for (my $Index = 1 ; $Index <= $Count ; ++$Index) {<br>
  321.       my $Document =
  322.   $AllDocuments->GetNthDocument($Index);<br>
  323.       printf "$Index. %s\n",
  324.   $Document->GetFirstItem('Subject')->{Text};<br>
  325.       my $Values =
  326.   $Document->GetItemValue('Index_Entries');<br>
  327.       foreach my $Value (@$Values) {<br>
  328.           print " Index:
  329.   $Value\n";<br>
  330.       }<br>
  331.       last unless $Index < 5;<br>
  332.   }</code></p>
  333. </blockquote>
  334. <p>You can access all objects that are accessible to LotusScript, and the
  335. LotusScript classes can be seen at <a class="doc" href="http://www.lotus.com/products/lotusscript.nsf">http://www.lotus.com/products/lotusscript.nsf</a>.
  336. A good idea would also be to read Jan Dubois article in TPJ#10 (visit The Perl
  337. Journal at <a class="doc" href="http://tpj.com/">http://tpj.com/</a>)</p>
  338.  
  339. <h2><a name="set_printer">How do I set the printer in Word?</a></h2>
  340. <p>The active printer can be set and retrieved through the word application
  341. object with <code>$Word->{ActivePrinter} = $printername</code>.</p>
  342.  
  343. <h2><a name="convert_vba">How do I convert a VBA macro to Perl?</a></h2>
  344. <p>If you record a macro in Microsoft Office, this can often be translated
  345. directly into Perl. In Visual Basic for Applications (VBA) the syntax is like
  346. this:</p>
  347. <blockquote>
  348.   <p><code>object.method(argument).property = value</code></p>
  349. </blockquote>
  350. <p>In Perl this becomes</p>
  351. <blockquote>
  352.   <p><code>object->method(argument)->{property} = value;</code></p>
  353. </blockquote>
  354. <p>So for example this code from VBA:</p>
  355. <blockquote>
  356.   <p><code>ActiveChart.Axes(xlCategory, xlPrimary).CategoryType =
  357.   xlCategoryScale</code></p>
  358. </blockquote>
  359. <p>becomes this in Perl:</p>
  360. <blockquote>
  361.   <p><code>$Chart->Axes(xlCategory, xlPrimary)->{CategoryType} =
  362.   xlCategoryScale;</code></p>
  363. </blockquote>
  364.  
  365. <h2><a name="find_docs">Where do I find documentation for the object models?</a></h2>
  366. <p>The best way to learn about methods/properties would be through an OLE type
  367. browser if the documentation is unavailable.</p>
  368. <p>If you have Microsoft Excel or Microsoft Word available, go into the Visual
  369. Basic Editor (Alt+F11). Now you can open the object browser window (F2) and see
  370. what you find.</p>
  371. <p>There is also an OleView program (various names and versions) included in
  372. Microsoft Visual C++ / Microsoft Visual Studio if you don't have Office. Or you
  373. can download it from the Microsoft COM website (<a class="doc" href="http://www.microsoft.com/com/">http://www.microsoft.com/com/</a>).</p>
  374. <p>But it is still possible that Notes doesn't reveal anything; objects are not
  375. required to provide type info support. For example Lotus Notes doesn't reveal
  376. nothing about it's internal constants, methods and properties; you have to look
  377. them up in the documentation.</p>
  378. <p>For Lotus Notes look at <a class="doc" href="http://www.lotus.com/products/lotusscript.nsf">http://www.lotus.com/products/lotusscript.nsf</a>.</p>
  379.  
  380.  
  381. <h2><a name="find_constants">OK, but can I at least find the constants that are exported from
  382. Win32::OLE::Const?</a></h2>
  383. <p>Yes, you can use the following code example to view all the constants - you
  384. really shouldn't need this, but if you want to know what's going on, it might
  385. help:</p>
  386. <blockquote>
  387.   <p><code>use strict;<br>
  388.   use Win32::OLE;<br>
  389.   use Win32::OLE::Const;<br>
  390.   <br>
  391.   my $xl = Win32::OLE::Const->Load("Microsoft Excel");<br>
  392.   printf "Excel type library contains %d constants:\n", scalar keys
  393.   %$xl;<br>
  394.   foreach my $Key (sort keys %$xl) {<br>
  395.       print "$Key = $xl->{$Key}\n";<br>
  396.   }</code></p>
  397. </blockquote>
  398. <p>Generally you should look at the documentation for Win32::OLE::Const.</p>
  399.  
  400. <h2><a name="errors">Why doesn't $! get set with the error message I am generating?</a></h2>
  401. <p>Error messages from Win32::OLE doesn't go to the $! variable, but can be
  402. accessed as <code>Win32::OLE->LastError()</code></p>
  403.  
  404. <h2><a name="odbc_ole">Why do I get an error when using ODBC and OLE?</a></h2>
  405. <p>For some reason you get an 'OleInitialize' error if you open an OLE
  406. application first and then open an ODBC connection to the Access ODBC driver. If
  407. you do it the other way around, there is no problem with this.</p>
  408. <p>It looks like the Access ODBC driver calls OleInitialize(). This fails when
  409. Win32::OLE already initialized the COM subsystem as "apartment
  410. threaded".</p>
  411. <p>In order to remove the error either start the ODBC driver before the OLE
  412. application or, better yet, initialize the OLE system with <code>Win32::OLE->Initialize(Win32::OLE::COINIT_OLEINITIALIZE);</code></p>
  413.  
  414. <h2><a name="strict">Why doesn't it work - even after all this?</a></h2>
  415. <p>Execute your scripts with <code>perl -w</code> and <code>use strict</code> -
  416. this catches most of your errors. Apart from this, read the documentation for
  417. Win32::OLE (a good start) and possibly the documentation for the object you are
  418. trying to use.</p>
  419. <p>In the case of Microsoft Office 97, make sure that you have at least updated
  420. to Service Release 1 - much of the OLE in Microsoft Office 97 is broken without
  421. this update.</p>
  422.  
  423. <h2><a name="AUTHOR_AND_COPYRIGHT">AUTHOR AND COPYRIGHT</a></h2>
  424. <p>This FAQ was compiled by Henning Michael M°ller-Nielsen of RTO based on
  425. examples by many people, especially Jan Dubois. It is maintained by Henning
  426. Michael M°ller-Nielsen, Philip Martin, Kevin Meltzer and Eric Smith at <a class="doc" href="mailto:perlwin32faq@rto.dk">perlwin32faq@rto.dk</a>.
  427. <p>This FAQ is in the public domain. If you use it, however, please ensure that
  428. you give credit to the original authors.</p>
  429.  
  430. <table border="0" cellpadding="0" cellspacing="0" width="100%">
  431.   <tr>
  432.     <td class="block" valign="MIDDLE" width="100%" bgcolor="#cccccc"><strong>
  433.       <p class="block"> ActivePerl FAQ - Using OLE with Perl</p>
  434.       </strong></td>
  435.   </tr>
  436. </table>
  437.  
  438. </body>
  439.  
  440. </html>
  441.