在Perl中编写OLE代码的简洁方法?

时间:2013-02-11 16:19:26

标签: perl ms-word interop ole

我正在通过Win32::OLE自动在Perl中创建Word文档。我当前的代码看起来像这样,它在内存中保留了WINWORD.EXE的实例:

my $range = $select->Range;
my $table = $doc->Tables->Add( $range, scalar @rows, scalar @{ $rows[0] } );
for my $rownum ( 0 .. $#rows ) {
    for my $colnum ( 0 .. $#{ $rows[$rownum] } ) {
        my @cellpos = ( $rownum + 1, $colnum + 1 );
        my $data = $rows[$rownum][$colnum];
        $table->Cell(@cellpos)->Range->{'Text'} = $data;
        1;
    }
}

但是,如果我按照Microsoft recommendation for Visual Studio .NET重构我的代码,它将如下所示:

my $range = $select->Range;
my $tables = $doc->Tables;
my $table = $tables->Add( $range, scalar @rows, scalar @{ $rows[0] } );
for my $rownum ( 0 .. $#rows ) {
    for my $colnum ( 0 .. $#{ $rows[$rownum] } ) {
        my @cellpos = ( $rownum + 1, $colnum + 1 );
        my $data = $rows[$rownum][$colnum];
        my $cell = $table->Cell(@cellpos);
        my $cell_range = $cell->Range;
        $cell_range->{'Text'} = $data;
    }
} 

那段代码完成了这项工作,但我的脑海里却非常“吵”。有更清洁的方法吗?

1 个答案:

答案 0 :(得分:1)

可以略微改善。不需要@cellpos$data变量,并且提取对@rows的当前元素的引用以在内循环中使用更为温和。

my $range = $select->Range;
my $tables = $doc->Tables;
my $table = $tables->Add( $range, scalar @rows, scalar @{ $rows[0] } );
for my $rownum ( 0 .. $#rows ) {
    my $cols = $rows[$rownum];
    for my $colnum ( 0 .. $#$cols ) {
        my $cell = $table->Cell($rownum + 1, $colnum + 1);
        my $cell_range = $cell->Range;
        $cell_range->{Text} = $cols->[$colnum];
    }
}