Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to cut text from a MS word document and paste that into another word document. Is there any way this can be handled in Perl?

Replies are listed 'Best First'.
Re: Copy, Cut, Paste Word document
by VSarkiss (Monsignor) on Nov 18, 2002 at 17:16 UTC

    Yes. The Win32::OLE module allows you to manipulate Word using the COM interface that it exposes. In other words, you'll need to understand the Word object model, and a little bit of COM in general. If you've written VBA macros for Word (or Excel or ....) you've gotten the flavor.

    There are some good resources here in the monastery. cacharbe has written a very good tutorial on using the Win32::OLE interface to Excel, which can help to get you started. You can also look up more resources and tutorials on Dave Roth's web site.

Re: Copy, Cut, Paste Word document
by jdporter (Paladin) on Nov 18, 2002 at 17:52 UTC
    As others have pointed out, Win32::OLE is probably the best way to go.

    Here is a simple solution that inserts the entire body of one document at the end of another document. It assumes that you want to manipulate the two documents' files on disk. If what you wanted to do was (for example) insert the contents of the current selection into another open document, that would be slightly more involved. In general, none of this kind of stuff is too complicated; but finding good references and examples can be kinda tough. In addition to the docs for the Win32::OLE modules, I found the Microsoft documentation for the Word object model to be indispensable.

    use Win32::OLE; use Win32::OLE::Const 'Microsoft Word'; my $source_doc = "X:\\source.doc"; my $dest_doc = "X:\\dest.doc"; my $Word = new Win32::OLE 'Word.Application', 'Quit'; $Word->Documents->open( $source_doc ) or die "Unable to open $source_doc ", Win32::OLE->LastError(); my $text = $Word->ActiveDocument->Content->Text; $Word->ActiveDocument->Close; $Word->Documents->open( $dest_doc ) or die "Unable to open $dest_doc ", Win32::OLE->LastError(); $Word->ActiveDocument->Content->InsertAfter({ Text => $text }); $Word->ActiveDocument->Close;
    This is just an example. You'd probably want to add more error handling, not to mention a better way of defining which document files are to be processed.

    jdporter
    ...porque es dificil estar guapo y blanco.

Re: Copy, Cut, Paste Word document
by John M. Dlugosz (Monsignor) on Nov 18, 2002 at 17:12 UTC
    Yes. Drive Winword.exe using OLE Automation. See the Win32::OLE module, and the "object model" documentation available for Office in conjunction with the Typelib Browser to figure out just what to call.

    —John

Re: Copy, Cut, Paste Word document
by talexb (Chancellor) on Nov 18, 2002 at 17:21 UTC

    I looked on CPAN -- and found just one reference: lhalw. This may not be the best place to look for this kind of software.

    --t. alex
    but my friends call me T.