无法在未定义的值上调用方法工作表

时间:2018-10-22 21:31:46

标签: excel perl

use strict;
use warnings;

use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::SaveParser;

my $excel_file_name = $ARGV[0];
my $parser          = Spreadsheet::ParseExcel::SaveParser->new();
my $workbook_orig   = $parser->Parse($excel_file_name);

# We will edit column 7 of the first worksheet.
my $worksheet = $workbook_orig->worksheet(0);
my $EDIT_COL = 6;

my ($row_min, $row_max) = $worksheet->row_range();
for my $r ($row_min .. $row_max){
    my $cell = $worksheet->get_cell($r, $EDIT_COL);
    unless (defined $cell){
        next; # Modify as needed to handle blank cells.
    }
    my $val = $cell->value . '_append_text';
    $worksheet->AddCell( $r, $EDIT_COL, $val, $cell->{FormatNo} );
}

# You can save the modifications to the same file, but when
# you are learning, it's safer to write to a different file.
$excel_file_name =~ s/\.xls$/_new.xls/;
$workbook_orig->SaveAs($excel_file_name);

我的上面的实现给我以下行中的错误“无法在未定义的值上调用方法工作表”。我正在尝试读取excel文件并解析该文件,以便以后可以向其中添加其他内容。我正在使用ParseExcel模块执行此操作,如果有任何更好的方法可以解决此问题,或者有任何关于为什么收到错误的指导,将非常感谢您的帮助。谢谢。

my $worksheet = $workbook_orig->worksheet(0);

1 个答案:

答案 0 :(得分:1)

Parse返回错误时的undef,您没有进行检查。试试:

my $workbook_orig   = $parser->Parse($excel_file_name);
unless ($workbook_orig) {
    die "Got error " . $parser->error() . " parsing spreadsheet.";
}

查看出现了什么错误,以便您决定如何解决。