2010-09-23 55 views
2

例如,我的docx文件包含以下句子:如何在Perl中使用Win32 :: Ole將格式應用於docx文件中的特定單詞?

這是一個Perl例如
這是一個Python的例子
這又是一個Perl的例子

我想大膽的風格適用於所有出現單詞「Perl的」像這樣的:

這是一個的Perl例如
這是一個Python示例
這是另一個的Perl例如

我已經走了這麼遠了下面的腳本:

use strict; use warnings; 
use Win32::OLE::Const 'Microsoft Word'; 

my $file = 'E:\test.docx'; 

my $Word = Win32::OLE->new('Word.Application', 'Quit'); 
$Word->{'Visible'} = 0; 
my $doc = $Word->Documents->Open($file); 
my $paragraphs = $doc->Paragraphs() ; 
my $enumerate = new Win32::OLE::Enum($paragraphs); 


while(defined(my $paragraph = $enumerate->Next())) { 

    my $text = $paragraph->{Range}->{Text}; 
    my $sel = $Word->Selection; 
    my $font = $sel->Font; 

    if ($text =~ /Perl/){ 
     $font->{Bold} = 1;    
    } 
    $sel->TypeText($text);   
} 

$Word->ActiveDocument->Close ; 
$Word->Quit; 

但它已申請大膽的風格,以全款,並沒有在他們原來的地方編輯的句子。它給了我兩個修改後的版本和原來的版本是這樣的:

這是一個Perl例如
這是一個Python的例子
這又是一個Perl的例子
這是一個Perl的例子
這是一個Python示例
這是另一個Perl示例

我應該如何解決我的問題。任何指針?由於像往常一樣:)

UPDATE

問題解決了!非常感謝@Zaid,並@cjm :)

下面是工作可愛的代碼:我不知道什麼的Perl

while (defined (my $paragraph = $enumerate->Next())) { 

    my $words = Win32::OLE::Enum->new($paragraph->{Range}->{Words}); 

    while (defined (my $word = $words->Next())) { 

     my $font = $word->{Font}; 
     $font->{Bold} = 1 if $word->{Text} =~ /Perl/; 
    } 
} 

回答

3

嘗試使用Words方法,而不是Text

未經測試:

while (defined (my $paragraph = $enumerate->Next())) { 

    my $words = Win32::OLE::Enum->new($paragraph->{Range}->{Words}); 

    while (defined (my $word = $words->Next())) { 

     my $font = $word->{Font}; 
     $font->{Bold} = 1 if $word->{Text} =~ /Perl/; 
    } 
} 
+0

@Zaid,感謝您的代碼。但perl的投我的錯誤「一點也不爲E的數組引用:\ test.pl第17行」。我認爲這意味着$ paragraph - > {Range} - > {Words}返回一個hashref,而不是一個數組ref。 – Mike 2010-09-23 05:55:28

+1

@Mike,嘗試'的Win32 :: OLE :: Enum->新($段落 - > {}範圍 - > {}詞)',就像你對段落做。(我建議避免使用間接對象語法;使用'Class-> new'而不是'New Class'。當使用間接對象語法時,Perl必須猜測它是方法調用還是普通函數,並且偶爾可以猜測錯誤。) – cjm 2010-09-23 06:34:29

+0

@Zaid和@cjm,感謝您的指導。現在這似乎更接近了。但@words數組不是單詞,標點符號等的集合。我使用print @words語句來打印它的內容,並且我正在接收類似下面的內容:Win32 :: OLE :: Enum = SCALAR(0x19c2f3c)。所以@words的內容既不是哈希引用,也不是數組引用,我不能使用$ word - > {Font} – Mike 2010-09-23 08:58:56

0

。 但是你看辦公室打開xml

你可以使用.docx文件作爲zip文件,並做一個簡單的搜索和替換,這比interop快一百萬倍。而且你也不必擔心可能出錯的數百萬事物。

重命名.docx文件爲.zip並打開它,你會明白我的意思。

相關問題