gambit20088 gambit20088 - 17 days ago 5
Perl Question

Perl - can't open file with Win32::OLE

I'm trying to open a

.docx
file using the following code:

require Win32::OLE;
my $docfile = "C:/Users/me/Documents/file.docx";
my $Word = Win32::OLE->GetActiveObject('Word.Application');
unless ($Word) { $Word = Win32::OLE->new('Word.Application', sub {$_[0]->Quit;}) or die "oops\n"; }
$Word->{visible} = 1;
my $File = $Word->Documents->Open($docfile);
$File->PrintOut();
$File->Close();
$Word->Quit();


But i get the following error:


OLE exception from "Microsoft Word":

Sorry, we couldn’t find your file. Is it possible it was moved,
renamed or deleted? (C://Users/me/Documents/...)


How can i fix this? Why does it add // to my path?
(needless to say, the file does exist in the system and that is the correct path).

Thanks!

Answer

I suggest that you use canonpath from File::Spec::Function to normalise the file path and change the path separators to backslashes

Like this

use strict;
use warnings 'all';

use Win32::OLE;
use File::Spec::Functions 'canonpath';

my $docfile = "C:/Users/me/Documents/file.docx";
my $word    = Win32::OLE->GetActiveObject('Word.Application');

unless ( $word ) {
    $word = Win32::OLE->new('Word.Application', sub {$_[0]->Quit;}) or die "oops\n";
}

$word->{visible} = 1;

my $file = $word->Documents->Open(canonpath($docfile)) or die;
$file->PrintOut;
$file->Close; 

$word->Quit;
Comments