【问题标题】:Can't call method "add_worksheet" on an undefined value?不能在未定义的值上调用方法“add_worksheet”?
【发布时间】:2015-08-01 13:24:55
【问题描述】:

这是我的 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. 

【问题讨论】:

  • 检查new()的返回值。 my $workbook = Spreadsheet::WriteExcel->new('perl.xls') or die "can't open?";
  • @Сухой27 它的返回打不开..
  • @sp1rs 找出原因? ...or die can't open: $!;

标签: excel perl cgi perl-module cgi-bin


【解决方案1】:

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

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

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

如果由于文件权限或其他原因无法创建文件 原因,new 将返回 undef。因此,最好的做法是 在继续之前检查new 的返回值。像往常一样,Perl 如果存在文件创建错误,将设置变量 $!。你会 另请参阅“DIAGNOSTICS”中详述的警告消息之一:

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

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

还值得从文档中指出这个警告:

注意:此模块处于仅维护模式,将来会 仅使用错误修复进行更新。更新、功能更丰富的 API 建议使用兼容的Excel::Writer::XLSX 模块。看, “Migrating to Excel::Writer::XLSX”。

【讨论】:

  • 它只有在你之前创建一个 .xls 文件并更改权限时才有效,那么它对我有用。谢谢 davecross。
  • 这不是真的。只要您的用户有权在目标目录中创建文件,它就会起作用。
猜你喜欢
  • 2014-10-31
  • 1970-01-01
  • 2016-11-26
  • 1970-01-01
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
相关资源
最近更新 更多