We help IT Professionals succeed at work.

How to create hash of arrays in perl from excel files ?

Michał Pijus
on
The format of input file is ( two columns in excel):

A1;A2
A1:B3
A1:C3
A2:C3
A2:D1

I'd like to get (make) something like that:

A1=>[A2,B3,C3];
A2=>[C3,D1];

No Idea ho to do it ;(
Comment
Watch Question

Depending on the Excel file format, you need to use either Spreadsheet::ParseExcel or Spreadsheet::XLSX (or Spreadsheet::ParseXLSX).

This should do what you want assuming that the data is in the first two columns of the first worksheet.
use strict;
use warnings;
use Spreadsheet::ParseExcel;
my $file = shift or die "Usage: $0 <input.xls>\n";
my $parser = Spreadsheet::ParseExcel->new();
my $wb = $parser->parse($file) or die $parser->error();
my $ws = ($wb->worksheets())[0];
my ($row_min, $row_max) = $ws->row_range();
my %hash;
for my $row ($row_min .. $row_max) {
    my $c1 = $ws->get_cell($row, 0)->value();
    my $c2 = $ws->get_cell($row, 1)->value();
    if (exists $hash{$c1}) {
        push @{$hash{$c1}}, $c2;
    } else {
        $hash{$c1} = [$c2];
    }
}
# do whatever you want with %hash

Open in new window

Beautiful work, wilcoxon!  I tested it on Windows and it worked for me.  Take a pay rise, and have the rest of the week off.

Michał, what kind of Excel files are you wanting to process?  XLS or XLSX?
If you want to process XLSX then, in theory, you should be able to just change "use Spreadsheet::ParseExcel" to "use Spreadsheet::ParseXLSX" in the code I provided.  Note though that I haven't actually used ParseXLSX (the syntax for Spreadsheet::XLSX code is a little different (it is compatible with an older version of Spreadsheet::ParseExcel)).
Thanks wilcoxon.
I changed the 2 occurrences of "Spreadsheet::ParseExcel" in your script to "Spreadsheet::ParseXLSX" and it worked for an XLSX file, just like a bought one.

Michał, what kind of Excel files are you wanting to process?  XLS or XLSX or both?  If both, wilcoxon's code could be easily modified to handle that, but you might be able to do that yourself.
Hi Michał,

I understand that this is your first question with Experts Exchange, so are you aware that to accept someone's answer, you don't just click the thumbs-up button.  You have to click the button under their post, near the right, to accept their answer, then follow the prompts.  Otherwise, the expert doesn't earn any points for their hard work.

Author

Commented:
Thank you wilcoxon. It works !