如何使用Win32:OLE更改msword的字符串中单词的colourindex?

时间:2010-03-17 03:54:06

标签: perl ms-word ole

我实际上是在尝试使用数组中的大括号更改第一个单词的颜色索引,以便它们在Word 2003中以正确的颜色显示。

例如,如果我有这样的数组:

@array="
        (This) is (perl),
         perl is a great (language),
         we can do anything with perl,
         (perl) feels us great."

我需要括号()内的第一个单词的颜色,即(This)(perl)包括()为红色,其余内容为黑色。并在MS Word 2003中打印数组的全部内容:

我正在使用Win32::OLE和Windows XP。这个数组只是一个例子,数组的内容会改变,但带括号的第一个单词必须用红色打印。

1 个答案:

答案 0 :(得分:2)

#!/usr/bin/perl

use strict; use warnings;
use Win32::OLE;
use Win32::OLE::Const 'Microsoft Word';
$Win32::OLE::Warn = 3;

my $word = get_app('Word.Application');
$word->{Visible} = 1;

my $doc = $word->Documents->Add;

while ( my $line = <DATA> ) {
    my @chunks = split /(\(\w+\))/, $line;
    my $seen;
    for my $chunk ( @chunks ) {
        my $sel = $word->Selection;
        my $font = $sel->Font;
        if ( $chunk =~ /^\(/ and not $seen) {
            $font->{ColorIndex} = wdRed;
            $seen = 1;
        }
        else {
            $font->{ColorIndex} = wdBlack;
        }
        $sel->TypeText($chunk);
    }
}

sub get_app {
    my ($class) = @_;
    my $app;
    eval {
        $app = Win32::OLE->GetActiveObject($class);
    };

    if ( my $ex = $@ ) {
        die $ex, "\n";
    }

    unless(defined $app) {
        $app = Win32::OLE->new($class, sub { $_[0]->Quit })
            or die "Oops, cannot start '$class': ",
                   Win32::OLE->LastError, "\n";
    }
    return $app;
}

__DATA__
(This) is (perl),
perl is a great (language),
we can do anything with perl,
(perl) feels us great.