1

我正在通过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 对 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;
    }
} 

该代码完成了这项工作,但在我看来它非常“嘈杂”。有没有更清洁的方法来做到这一点?

4

1 回答 1

1

它可以稍微改进。不需要@cellposand$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];
    }
} 
于 2013-02-11T19:22:24.613 回答