3

我正在尝试打开一个 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“打开”

更新:我可以很好地打开 Word 应用程序,只是当我尝试打开文件时出现问题

4

2 回答 2

4

我有几个脚本可以使用Win32::OLE将 DOC 转换为各种输出格式。他们通常是这样开始的:

use Win32::OLE;
use Win32::OLE::Const 'Microsoft Word';
my $wr = Win32::OLE->new('Word.Application')
    or die "Failure - word. \n";

$wr->{DisplayAlerts} = wdAlertsNone;
$wr->{Visible} = 0;

my $Doc = $wr->Documents->Open({
    FileName           => $input_file_path,
    ConfirmConversions => 0,
    AddToRecentFiles   => 0,
    Revert             => 0,
    ReadOnly           => 1,
    OpenAndRepair      => 0,
}) or exit;

...

请注意,$input_file_path必须包含文件的绝对路径。您还可以启用VisibleDisplayAlerts查看 Word 可能给您的任何错误。

编辑:in您可以使用枚举器遍历段落:

use Win32::OLE qw(in);

...

my $paragraphs = $Doc->Paragraphs;
for my $par (in $paragraphs) {
    print $par->Range->Text();
}

或者您可以使用 Word 自己的导出方法并将文档另存为支持的格式之一:

$Doc->SaveAs({
    FileName   => 'c:\\work\\Test.txt',
    FileFormat => wdFormatEncodedText,
});

后一种方法的优点是尽可能保留格式,从而为项目符号、编号等产生更好的结果。

于 2011-07-16T14:07:41.277 回答
1

Win32::OLE关于交互可能有点有趣。如果有任何触发提示,您可能会收到这样的消息。例如,通常它可能希望以只读方式打开文件并打开一个对话框,但这些对话框可能会在Win32::OLE.

如果是这种情况,请致电

Win32::OLE->Initialize(Win32::OLE::COINIT_OLEINITIALIZE);

在你做任何像实例化任何对象(即 before Win32::OLE->new)之类的事情之前可能会成功。

于 2011-07-15T15:21:11.447 回答