Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a multidimensional array (AoA) to Excel using Perl?

I want to add my data stored in 2x2 dimension array in Excel using Perl. I know how to open and add simple data. This I can do using for loop. But how can I do it elegantly?

This is what I am trying to do

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

where @data is two dimensional array.

# 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;

1 Answers

I see that you are using Win32::OLE but this sort of thing is also quite easy with 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 );
like image 148
jmcnamara Avatar answered Dec 08 '25 10:12

jmcnamara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!