不能调用方法“add_worksheet”未定义的值?

这里是我的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 :: WriteExcel中 new()方法的文档。 它说:

如果文件无法创build,由于文件权限或其他原因, new将返回undef 。 因此,在继续之前检查new的返回值是一个很好的做法。 像往常一样,Perlvariables$! 将会被设置,如果有文件创build错误。 您还将看到“ 诊断 ”中详细介绍的警告消息之一:

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

我猜你的CGI程序正在试图写入一个没有所需权限的目录中的文件。 您可能需要将new()指向要创build文件的目录的完整path。

从文档中指出这个警告也是值得的。

注意:此模块处于仅维护模式 ,将来只会更新错误修复。 build议使用更新,function更丰富,API兼容的Excel :: Writer :: XLSX模块。 请参阅“ 迁移到Excel :: Writer :: XLSX ”。