Tom Macdonald
Tom Macdonald

Reputation: 6583

iterate over Excel file in perl using Spreadsheet::Read

I am trying to parse data from an excel file (can be xlsx or xls).

I already know which worksheets I want to get, so I would like to iterate over them and extract the data from them.

My code :

#!/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) {

  }
}

However, I get the following :

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

I'm very new to perl, and don't understand yet the intricacies of hashes, arrays and references.

Upvotes: 1

Views: 2895

Answers (2)

mpapec
mpapec

Reputation: 50637

First don't use array if you don't need it,

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

Print $sheet reference to check instance of $sheet if error still occurs.

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

It look like your data should be accessed in another way, this is from 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",
    :
    :
]

so if you want to read label from $sheet it would be $sheet->{label}, and so on.

Upvotes: 3

choroba
choroba

Reputation: 241808

The problem is the following:

@sheet->row_range

You cannot use a method on a non-object. Object must be a reference, i.e. a scalar. It should start with a $, not @.

Upvotes: 1

Related Questions