たとえば、私の 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 の例です
問題を解決するにはどうすればよいですか。ポインタはありますか?いつもありがとう:)
アップデート
問題が解決しました!@Zaidと@cjmに感謝します:)
素敵に機能するコードは次のとおりです。
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/;
}
}