无法对未定义的值调用方法 "add_worksheet"?

Can't call method "add_worksheet" on an undefined value?

这是我的 cgi 代码,perl.xls 文件作为脚本存在于保存文件夹中。

 #!/usr/bin/perl
 print "Content-type: text/html\n\n";
 use CGI;
 use DBI;
 use Spreadsheet::WriteExcel;
 use strict;
 use warnings;
 use CGI::Carp qw(fatalsToBrowser);
 my $cgi = CGI->new;
 my $workbook = Spreadsheet::WriteExcel->new('perl.xls');
 my $worksheet = $workbook->add_worksheet();
 $worksheet->write(0,0,'value');

当我 运行 脚本时我得到这个错误

Software error:

Can't call method "add_worksheet" on an undefined value at /var/www/cgi-bin/excel.cgi line 17.

 For help, please send mail to the webmaster (root@localhost), giving this error message and the time and date of the error. 

错误信息很清楚。您正在对未定义的值调用方法 (add_worksheet())。您在 $workbook 上调用该方法,因此您需要调查该值的设置方式。它来自这一行:

my $workbook = Spreadsheet::WriteExcel->new('perl.xls');

因此,可能值得查看 Spreadsheet::WriteExcelnew() 方法的文档。它是这样说的:

If the file cannot be created, due to file permissions or some other reason, new will return undef. Therefore, it is good practice to check the return value of new before proceeding. As usual the Perl variable $! will be set if there is a file creation error. You will also see one of the warning messages detailed in "DIAGNOSTICS":

my $workbook  = Spreadsheet::WriteExcel->new('protected.xls');
die "Problems creating new Excel file: $!" unless defined $workbook;

我猜你的 CGI 程序正试图在没有所需权限的目录中写入文件。您可能需要 new() 应创建文件的目录的完整路径。

还值得指出文档中的警告:

Note: This module is in maintenance only mode and in future will only be updated with bug fixes. The newer, more feature rich and API compatible Excel::Writer::XLSX module is recommended instead. See, "Migrating to Excel::Writer::XLSX".