1

我正在尝试从 excel 文件(可以是 xlsx 或 xls)中解析数据。

我已经知道我想要获得哪些工作表,所以我想遍历它们并从中提取数据。

我的代码:

#!/usr/bin/perl -w

use strict;
use warnings;
use Spreadsheet::Read;
use Getopt::Long;

my $inputfile;

GetOptions (
  'i=s' => \$inputfile,
);

die 'missing input file' unless $inputfile;

my $workbook  = ReadData ($inputfile, debug => 9);
my @worksheets = (1);
foreach (@worksheets) {
  my $sheet = $workbook->[$_-1];

  next unless $sheet;

  my ( $row_min, $row_max ) = $sheet->row_range();
  my ( $col_min, $col_max ) = $sheet->col_range();
  for my $row ($row_min .. $row_max) {

  }
}

但是,我得到以下信息:

Can't call method "row_range" on unblessed reference at perl/parse_test.pl line 22.

我对 perl 很陌生,还不了解散列、数组和引用的复杂性。

4

2 回答 2

3

首先不要使用数组,如果你不需要它,

my @sheet = $workbook->[$_-1];=>my $sheet = $workbook->[$_-1];

打印$sheet参考以检查$sheet是否仍然发生错误。

next unless $sheet;
print ref($sheet), "\n";

看起来您的数据应该以另一种方式访问​​,这是来自http://metacpan.org/pod/Spreadsheet::Read#Data-structure

$book = [
  # Entry 0 is the overall control hash
  { sheets  => 2,
    sheet   => {
      "Sheet 1"  => 1,
      "Sheet 2"  => 2,
      },
    type    => "xls",
    parser  => "Spreadsheet::ParseExcel",
    version => 0.59,
    },
  # Entry 1 is the first sheet
  { label   => "Sheet 1",
    maxrow  => 2,
    maxcol  => 4,
    cell    => [ undef,
      [ undef, 1 ],
      [ undef, undef, undef, undef, undef, "Nugget" ],
      ],
    A1      => 1,
    B5      => "Nugget",
    },
  # Entry 2 is the second sheet
  { label   => "Sheet 2",
    :
    :
]

$sheet因此,如果您想从中读取标签,则为$sheet->{label},依此类推。

于 2013-05-16T14:32:19.013 回答
1

问题如下:

@sheet->row_range

您不能对非对象使用方法。对象必须是引用,即标量。它应该以 开头$,而不是@

于 2013-05-16T14:31:42.863 回答