【发布时间】:2012-08-22 09:33:01
【问题描述】:
我搜索了答案,但没有找到答案,所以它让我在 stackowerflow 注册。我正在尝试使用 win32 ole 编写简单的 perl 脚本,它将遍历所有 M$ 单词段落(任何以硬返回结尾的文本)并仅打印与指定条件匹配的那些段落。问题是我需要访问字体大小属性。在我看来,这个属性在第一段中只设置了一次,之后没有更新。请看以下代码:
#!/usr/bin/perl
use strict;
use warnings;
use Win32::OLE::Const 'Microsoft Word';
#$Win32::OLE::CP = CP_UTF8;
binmode STDOUT, 'encoding(utf8)';
# OPEN FILE SPECIFIED AS FIRST ARGUMENT
my $fname=$ARGV[0];
my $fnameFullPath = `cygpath.exe -wa $fname`;
$fnameFullPath =~ s/\\/\\\\/g;
$fnameFullPath =~ s/\s*$//;
unless (-e $fnameFullPath) { print "Error: File did not exists\n"; exit 1;}
# STARTING OLE
my $Word = Win32::OLE->GetActiveObject('Word.Application')
|| Win32::OLE->new('Word.Application','Quit')
or die Win32::OLE->LastError();
$Word->{'Visible'} = 0;
my $doc = $Word->Documents->Open($fnameFullPath);
my $paragraphs = $doc->Paragraphs() ;
my $enumerate = new Win32::OLE::Enum($paragraphs);
# PROCESSING PARAGRAPHS
while(defined(my $paragraph = $enumerate->Next())) {
my $text = $paragraph->{Range}->{Text};
my $sel = $Word->Selection;
my $font = $sel->Font;
if ($font->{Size} == 18){
print "Text: ", $text, "\n";
print "Font Bold: ", $font->{Bold}, "\n";
print "Font Italic: ", $font->{Italic}, "\n";
print "Font Name: ", $font->{Name}, "\n";
print "Font Size: ", $font->{Size}, "\n";
print "=========\n";
}
}
# CLOSING OLE
$Word->ActiveDocument->Close ;
$Word->Quit;
这是我得到的输出:
Text: This is a doc file containing different fonts and size, document also contain header and footer (Font: TNR, Size: 18)
Font Bold: 0
Font Italic: 0
Font Name: Times New Roman
Font Size: 18
=========
Text: This is a Perl example (Font TNR, Size: 12)
Font Bold: 0
Font Italic: 0
Font Name: Times New Roman
Font Size: 18
=========
Text: This is a Python example(Font: Courier New, Size: 10)
Font Bold: 0
Font Italic: 0
Font Name: Times New Roman
Font Size: 18
=========
正如您在输出中看到的那样,字体大小为 18,即使原始文档中的大小不同(字体名称也未更新)。这让我假设 $font 在处理的第一段中只设置一次。因此以下条件
if ($font->{Size} == 18)
仅在第一个处理的段落中进行评估。这也支持如果我将条件更改为以下(匹配第 2 段)的事实:
if ($font->{Size} == 12)
输出什么都没有。因为第一段是 18 而不是 12,因此条件为假,$font 不再更新,所以它永远不会是真的。我做错了什么?
非常感谢
【问题讨论】:
-
在我看来,段落样式的默认字体是 Times Roman,大小 18。
-
虽然我承认,我对这个模块不太熟悉,但我想知道
$Word->Selection应该做什么。也许它只收集第一段的信息? -
使用查询
$paragraph->{Range}怎么样?喜欢$sel = $paragraph->Range; $text = $sel->Text; $font = $sel->Font;? -
您好,抱歉回复时间较长。 AFAIK $Word->Selection is acutually selected part (header, main, footer) 也尝试过 raina77ow 建议但没有运气
标签: perl ms-word selection ole