ravi179 has asked for the wisdom of the Perl Monks concerning the following question:

how to Read the data in excel and store it as Hash?

My Excel is in given format.

ID NAME Degree Collage

1 Teja B.Tech NIT

M.Tech IIT(the problem is in converting this line)

2 Ravi B.tech MIT

I am in a position to convert a Excel table into a key value pairs.Please help me.Thanks in advance.

use Spreadsheet::ParseExcel; $filename = shift || "Book2.xls"; $e = new Spreadsheet::ParseExcel; $eBook = $e->Parse($filename); $sheets = $eBook->{SheetCount}; $eSheet = $eBook->{Worksheet}[$sheet]; for my $row(1 .. $eSheet->{MaxRow}) { next unless (defined $eSheet->{Cells}[$row][$col]); my $master_key=$eSheet->{Cells}[$row][0]->Value; for my $col(1 .. $eSheet->{MaxCol}) { next unless (defined $eSheet->{Cells}[$row][$col]); my $key= $eSheet->{Cells}[0][$col]->Value; my $value = $eSheet->{Cells}[$row][$col]->Value; $data{$master_key}->{($key)}=$value; } } for $id(sort keys %data) { print "$id:\n "; for $role(sort keys%{$data{$id}}) { print " $role=$data{$id}{$role}\n"; } print "\n"; }

Replies are listed 'Best First'.
Re: Converting Excel to Hash
by Corion (Patriarch) on Jan 03, 2017 at 08:04 UTC

    What does your code output?

    What output do you expect instead?

      Expected Output

      { '1'=> { 'clz=>'nit' 'degree'=>'ph.d', 'name'=>'teja' }, '1'=> { 'clz=>'iit' 'degree'=>'M.tech', 'name'=>'teja' },####This block not coming in output '2'=>{ 'clz=>'mit' 'degree'=>'ravi', 'name'=>'B.Tech' } };

        A hash cannot have multiple values for the same key. You will need to rethink your data structure.

        Consider storing array references as values instead of hash references as values:

        { '1'=> [{ 'clz=>'nit' 'degree'=>'ph.d', 'name'=>'teja' }, { 'clz=>'iit' 'degree'=>'M.tech', 'name'=>'teja' }],####This block not coming in output '2'=>[{ 'clz=>'mit' 'degree'=>'ravi', 'name'=>'B.Tech' }] };

        This change will also need changes in your code on how you fill the data structure and how you output your data structure.