I am working with the Spreadsheet::ParseExcel module. I want to create a hash of hash with the Excel data:
{
'P343453' => {
'Date' => 03022011,
'Method' => 'No',
'Time' => 1440,
},
'P343763' => {
'Date' => 03022011,
'Method' => 'YES',
'Time' => '1745',
}
}
What I have now is something like this:
{
'P343453' => [
'03022011',
'No',
'1440',
],
'P343763' => [
'03022011',
'YES',
'1745',
],
}
Here is my code:
my @worksheets = $workbook->worksheets();
warn "More than 1 worksheet found\n" if @worksheets > 1;
# Only work with first page.
my $worksheet = $worksheets[0];
my ( $row_min, $row_max ) = $worksheet->row_range();
my ( $col_min, $col_max ) = $worksheet->col_range();
my @required_col = (1 .. $col_max);
my @value;
##to get the headers of the excel file;
for my $row ( 0 .. 0 ) {
@value = map {
my $cell = $worksheet->get_cell($row, $_);
$cell ? $cell->value() : '';
} @required_col;
}
# Skip header row
my $sample_details = {};
for my $row (1 .. $row_max ) {
my @data = map {
my $cell = $worksheet->get_cell($row, $_);
$cell ? $cell->value() : '';
} @required_col;
$sample_details->{$worksheet->get_cell($row,0)->value()} = \@data
if defined $worksheet->get_cell($row, 0)->value();
}
How should I modify the code to assign the keys to the hashrefs of the hash from the array @value
?
# Skip header row
my $sample_details = {};
for my $row (1 .. $row_max ) {
my @data = map {
my $cell = $worksheet->get_cell($row, $_);
$cell ? $cell->value() : '';
} @required_col;
foreach my $col (@values) {
$sample_details->{$worksheet->get_cell($row,0)->value()}{$col} = shift @data if defined $worksheet->get_cell($row, 0)->value();
}
}
Replace the \\@data
in the last line with this:
{ map { ($value[$_] => $data[$_]) } (0..$#value) }
This will make a key/value pair from each list value using the corresponding header as key.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.