我想从excel文件中读取数据并将其存储到数组的Hash中。
例如,我有一个Excel文件如下:
我想从数据表中获取值并将其存储为:
%hash = (
"A1" => [ "B1", "C1", "D1" ],
"A2" => [ "B2", "C2", "D2" ],
"A3" => [ "B3", "C3", "D3" ]
);
我已安装Spreadsheet::Read
并使用以下方法存储它。
#!/usr/bin/perl
use Spreadsheet::Read;
my $workbook = ReadData ("test.xls");
my %hash = (
"$workbook->[1]{A2}" => ["$workbook->[1]{B2}","$workbook->[1]{B3}"]
);
print $hash{"$workbook->[1]{A2}"}->[1];
但它并不聪明。如何更有效地存档呢?
有人可以给我一些建议吗?
答案 0 :(得分:1)
我认为您要求的是一个更通用的程序,它将处理包含任意数量的行和列的电子表格
我根据documentation for Spreadsheet::Read
写了这个,它说它导出一个row
函数,它会返回给定电子表格给定行号中元素的数组
我无法对此进行测试,因为我没有安装Excel副本,但它确实编译成功,而且相当简单,所以我没有预料到任何问题
#!/usr/bin/perl
use strict;
use warnings 'all';
use Spreadsheet::Read qw/ ReadData row /;
my $workbook = ReadData('test.xls', rc => 1, cells => 0);
my $sheet = $workbook->[1];
my %data;
for my $i ( 1 .. $sheet->{maxrow} ) {
my ($col1, @rest) = row($sheet, $i);
$data{ $col1 } = \@rest;
}
use Data::Dumper;
print Dumper \%data;
答案 1 :(得分:-1)
问题非常简单。首先计算Excel工作表中行和列的总数。然后在哈希值中插入值
#!/usr/bin/perl
use Spreadsheet::Read;
my $worksheet = ReadData ("test.xls");
my $workbook = $worksheet->[1]; #excel sheet no
#row count....
my $max_rows = $workbook->{'maxrow'};
#column count...
my $max_cols = $workbook->{'maxcol'};
my %hash ;
for my $row_num (1..($max_rows))
{
if(exists $workbook->{'cell'}[1][$row_num])
{
#insert values in the hash
my $id = $workbook->{'cell'}[1][$row_num];
my $val1 = $workbook->{'cell'}[2][$row_num];
my $val2 = $workbook->{'cell'}[3][$row_num];
my $val3 = $workbook->{'cell'}[4][$row_num];
push (@{$hash{$id}},$val1, $val2, $val3);
}
}
#hash Reading
foreach my $id (keys %hash)
{
my @arr = @{$hash{$id}};
print "$id\t@arr\n";
}
您可以根据需要修改哈希插入过程