Question : Perl - Read Excel rows into an array

I have been playing with Spreadsheet::BasicRead module and a few others with no luck.  What I want to do is have the script read an excel file and parse each row into an array.  Can someone give me some example code?

Answer : Perl - Read Excel rows into an array

I thought the comments in the code were sufficient.  I'll try explaining better.

If you don't understand nested data structures in perl, I would suggest looking at a tutorial (I think one was http://www.perltutorial.org/).

Let me know if there is still anything you don't understand.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
# you should always use strict and warnings to reduce errors in your code
use strict;
use warnings;
use Spreadsheet::ParseExcel;
my %data;
# create the parser object
my $parser = Spreadsheet::ParseExcel->new();
# open the xls file
my $xls = $parser->parse('/var/tmp/now.xls') or die $parser->error();
# loop over all worksheets in the file
foreach my $sheet ($xls->worksheets()) {
    my ($rmin, $rmax) = $sheet->row_range();
    my ($cmin, $cmax) = $sheet->col_range();
    my @page;
    for my $row ($rmin..$rmax) {
        my @line;
        for my $col ($cmin..$cmax) {
            my $cell = $sheet->get_cell($row, $col);
            push @line, $cell->value() if defined($cell);
        }
        # @line now contains an array of the current line
        push @page, [@line];
    }
    # @page now contains an array of arrays of all lines on the current worksheet
    # example code of what to do with @page
    foreach my $line (@page) { # loop over each line
       # $line is now an arrayref
       # print each line with spaces between columns
       print "@$line\n";
       # more generally, this could be (and you could replace space with whatever):
       # print join(' ', @$line), "\n";
    }
    # end example
    $data{$sheet->get_name()} = [@page];
}
# %data now contains a hash of arrays of arrays of all data in the Excel
# example code (commented out) of how to print out all data for all pages
# foreach my $name (sort keys %data) {
#     print "Worksheet $name\n";
#     foreach my $line (@{$data{$name}}) {
#         print join(' ', @$line), "\n";
#     }
# }
Random Solutions  
 
programming4us programming4us