使用 Perl 写入 Excel 文件

Writing to Excel File with Perl

这是我的第一次尝试,我正在尝试了解使用的基础知识 Excel::Writer::XLSX。我的脚本似乎无法编译。

#!C:\Perl\bin
#excel::writer attempt
#allows IR-Serial-Parts tracking

use strict;
use warnings;
use POSIX qw(strftime);
use Excel::Writer::XLSX;


my $ref = strftime '%Y-%m-%d', locatime();      #create the datestamp
my $file = "$ref.xlsx";
my $workbook = Excel::Writer::XLSX->new('$file');   #declare it outside of if loop preventing original issue.
#if(-e $file){
#       my $workbook = Excel::Writer::XLSX->open('$file');  #open existing  excel file
#}
#else{
#       my $workbook = Excel::Writer::XLSX->new('$file');   #open new Excel   if the date on comp has changed
#}

$worksheet = $workbook->add_worksheet("Tracking");
$worksheet->write( 'A1', 'Hi Excel!');

我什至不需要做任何事情,我只是想测试写入电子表格中的单元格,但我什至无法做到这一点。我觉得我现在很难做到这一点。这是 shell returns.

Global symbol "$worksheet" requires explicit package name at writexcel.pl         line 20.
Global symbol "$workbook" requires explicit package name at writexcel.pl line   20
.
Global symbol "$worksheet" requires explicit package name at writexcel.pl      line 21.
Execution of writexcel.pl aborted due to compilation errors.
Press any key to continue . . .

至此原问题得到解答。

Undefined subroutine &main::locatime called at writexcel.pl line 11.
Press any key to continue . . .

我的新错误。我认为这可能与 strftime 有关,但我不太确定。

尝试在循环外声明 $workbook 变量。 此外,当您使用 strict 时,您需要使用 my:

声明 $worksheet
use strict;
use warninigs;

my $workbook;

if(-e $file){
        $workbook = Excel::Writer::XLSX->open($file);  
}
else{
        $workbook = Excel::Writer::XLSX->new($file); 
}

my $worksheet = $workbook->add_worksheet('Tracking');
$worksheet->write( 'A1', 'Hi Excel!');
my $workbook = Excel::Writer::XLSX->new('$file');

此行不会创建名称存储在 $file 变量中的文件,而是创建具有确切名称 $file.

的文件

在循环外使用 "my" 声明 $workbook 和 $worksheet

参考https://github.com/AarthiRT/Excel_Writer_XLSX