如何使用Perl向Excel添加多维数组(AoA)?

时间:2009-04-08 11:00:46

标签: perl arrays excel multidimensional-array

我想使用Perl在Excel中添加存储在2x2维数组中的数据。我知道如何打开和添加简单数据。我可以使用for循环。但我怎么能优雅地做到这一点?

这就是我想要做的事情

$sheet->Range("A1:B"."$size")->{Value} = @$data;
                                         or   @data;
                                         or   {@data};
                                         or   {\@data};

其中@data是二维数组。

# use existing instance if Excel is already running
eval {$ex = Win32::OLE->GetActiveObject('Excel.Application')};
die "Excel not installed" if $@;
unless (defined $ex) {
    $ex = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;})
            or die "Oops, cannot start Excel";
}


# get a new workbook
$book = $ex->Workbooks->Add;

# write to a particular cell
$sheet = $book->Worksheets(1);
print "A1:B"."$size";
# write a 2 rows by 3 columns range

$sheet->Range("A1:B"."$size")->{Value} = @$data;

2 个答案:

答案 0 :(得分:3)

我看到你正在使用Win32 :: OLE,但Spreadsheet::WriteExcel这种事情也很容易:

#!/usr/bin/perl -w

use strict;
use Spreadsheet::WriteExcel;

my $workbook  = Spreadsheet::WriteExcel->new('test.xls');
my $worksheet = $workbook->add_worksheet();

# Get your AoA from somewhere.
my $data = [
    [ 'Hello', 'world', 123   ],
    [ 'Bye',   'bye',   4.567 ],
];

# Write the data.
$worksheet->write_col( 'A1', $data );

答案 1 :(得分:2)

基于一些阅读(我前面没有Win32框),看起来Value的{​​{1}}属性正确处理对AoA的引用,所以试着说:

Range