Search code examples
perlexport-to-excelperl-module

Writing to Excel File with Perl


This is my first attempt and I'm trying to get the basics down of using Excel::Writer::XLSX. I can't seem to get my script to even compile.

#!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!');

I haven't even had to do anything yet I simply just wanted to test writing to a cell in an spreadsheet, and I can't even manage to do that. I feel like I'm making this to hard right now. Here's what the 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 . . .

Now that the original question is answered.

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

my new error. I think it may have something to do with strftime but I'm not quite sure.


Solution

  • Try declaring the $workbook variable outside of your loops. Also, as you're using strict you need to declare $worksheet using my:

    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!');