Perl-can';无法使用Win32::OLE打开文件

Perl-can';无法使用Win32::OLE打开文件,perl,Perl,我正在尝试使用以下代码打开.docx文件: 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 "o

我正在尝试使用以下代码打开
.docx
文件:

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();
但我得到了以下错误:

“Microsoft Word”中的OLE异常:

很抱歉,我们找不到您的文件。有没有可能它被移动了, 重命名还是删除?(C://Users/me/Documents/…)

我怎样才能解决这个问题?为什么它会将//添加到我的路径中? (不用说,文件确实存在于系统中,这是正确的路径)


谢谢

我建议您使用
canopath
from
File::Spec::Function
来规范文件路径,并将路径分隔符更改为反斜杠

像这样

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') or die;

$word->{visible} = 1;

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

$word->Quit;

我从未使用过Win32::OLE,所以这只是一个猜测。也许它想在路径中使用反斜杠?但是请注意,如果你重复引用,你可能需要避开它们。这是哪个版本的单词?我没有最新的版本,但可能它试图将其视为UNC或其他东西。在任何情况下,如果只使用
my$docfile=join'\\',qw(C:Users-me-Documents-file.docx),会发生什么?另外,
使用Win32::OLE$Win32::OLE::Warn=3并非Windows上的所有内容都接受
/
作为目录分隔符。您可能需要将其写成
my$docfile='C:\\Users\\me\\Documents\\file.docx'
双斜杠是必需的,因为
\
是转义字符。还有一个显而易见的问题。。。你真的确定
C:\Users\me\Documents\file.docx
存在并且可读吗?使用
-r$docfile
@Schwern在代码中检查它是的,我确定,不幸的是它不起作用。使用此解决方案,我如何将文件的内容打印到控制台?(作为文本)只能使用
Win32::OLE
执行可以使用Word应用程序手动执行的操作。您不能显示Word中的纯文本,因此也不能这样做。好的。。那我怎么做呢?我应该创建一篇新文章吗?您可以使用Perl和
Win32::OLE
另存为。。。将文档转换为文本文件,然后在同一程序中读取和打印该文件。我已经结束了你的问题,因为它是另一个有替代解决方案的问题的复制品。如果你需要更多的帮助,是的,问另一个问题。