【发布时间】:2011-10-06 05:07:00
【问题描述】:
我正在尝试打开一个 word 文档,然后提取文档中的所有文本并使用 Win32::OLE 将其显示给用户
#usr/bin/perl
#OLEWord.pl
#Use string and print warnings
use strict;use warnings;
#Using OLE + OLE constants for Variants and OLE enumeration for Enumerations
use Win32::OLE;
use Win32::OLE::Const 'Microsoft Word';
$Win32::OLE::Warn = 3;
#set the file to be opened
my $file = '/work/Test.docx';
#Create a new instance of Win32::OLE for the Word application, die if could not open the application
my $MSWord = Win32::OLE->new('Word.Application','Quit') and "Opened Word" or die "Unable to open document ", Win32::OLE->LastError();
#Set the screen to Visible, so that you can see what is going on
$MSWord->{'Visible'} = 1;
#open the request file or die and print warning message
my $Doc = $MSWord->Documents->Open('C:\work\Test.docx') or die "Could not open ", $file, " Error:", Win32::OLE->LastError();
#$MSWord->ActiveDocument->SaveAs({Filename => 'AlteredTest.docx',
#FileFormat => wdFormatDocument});
sub ShowObjs {
my $obj = shift;
foreach (sort keys %$obj) {
print "Keys: $_ - $obj->{$_}\n"; }
}
my $paragraphs = $Doc->Paragraphs;
ShowObjs($paragraphs);
# Get and print the Text inside the opened file
my $paragraphs = $Doc->Paragraphs;
my $txt = $Doc->Range->Text;
print $txt;
$MSWord->ActiveDocument->Close;
$MSWord->Quit;
我收到此错误代码:
“Microsoft Word”的 OLE 异常:
命令失败
Win32::OLE(0.1709) 错误 ox800a1066 在 OLEWord.pl 第 20 行的 METHOD/PROPERTYGET "Open" 中
更新:我可以正常打开 Word 应用程序,只是当我尝试打开文件时出现问题
【问题讨论】:
-
您确定文件扩展名是“doc”吗?打开失败让我觉得文件扩展名是docx,而不是doc。
-
我把文件改成docx还是不行
-
我可以使用上面的脚本打开 Word 文件(doc 和 docx)(但在
$txt = $Word->Paragraphs...上会失败)。您是否有权打开该文件并且该文件尚未在 Word 中的其他位置打开? -
是的,我创建了用于测试的文件,我也不确定如何从单词 docuemtn 中获取文本
-
确保文件可访问。尝试使用绝对路径。