Who is this for
This article discusses on how to write perl scripts to communicate with Microsoft Office documents through OLE. This will work only on Windows operating system and if you have Microsoft Office installed on your machine.
What you need to know
Perl programmingIntroduction
Let us say that you have a database that you need to extract data from. Since you need to extract data that will be easier done in Perl than in another proprietary software, you wrote the program in Perl. But then, you need to generate a Microsoft Word document. How do you do that?
Well, there is hope because Perl has a module called Win32:OLE. This module allows you to communicate with Microsoft Office components to generate Microsoft Office documents.
First things first
First thing you need is to install the Win32 and the Win32::OLE modules. Once you have done this, you have to specify this in your script:
use Win32::OLE
Initialize your environment
The first thing to do is to check if you have Microsoft Word installed. This is done through this statement:
my $x = Win32::OLE->GetActiveObject('Word.Application') ;
If everything is installed, $x will return a reference to a Win32::OLE object.
If Word is installed, you have to start it. You do this by:
my
$word = Win32::OLE->new('Word.Application', sub { $_[0]->Quit;
} )
The new method of the OLE module starts Word. The second parameter is a routine that executes when Word terminates. It can be a subroutine or an OLE method
Create your document
Now that Word has started, you need to create a new document. In VBA, you create a new document using this instruction: Documents.Add
In Perl, you write:
my
$doc = $word->Documents->Add;
my $select = $word->Selection;
Notice how similar the instructions are? You execute the Add method of the Documents object referred by the $word object.
To add text to the document, you need to add it to the Selection.
my $text = "This is the first line\n";
$select->TypeText($text);
To change the font of the text, you need to define the Range.
Go To Page: 1 2
| Here's the follow-up discussion on this article: | View all related messages |
For a complete listing of article comments, questions, and other discussions related to Philip Yuson's Perl topic, please visit the Discussions page.