Home » excel » perl – How to handle excel using OLE module?

perl – How to handle excel using OLE module?

Posted by: admin April 23, 2020 Leave a comment

Questions:

Friends, I wrote a Perl script to convert a set of CSV files into spreadsheet
format using Spreadsheet::WriteExcel. After some research I came to
conclusion that there is no option to fix column width as Auto-fit option.

So what I’m doing is in the same script I’ve opened that XLS file using Win32::OLE
module, while doing this I got an error message

Can't use an undefined value as a HASH reference

Corresponding code is:

# spread sheet creation
my $workbook  = Spreadsheet::WriteExcel->new($file_name);
# ...
my $worksheet = $workbook->add_worksheet($work_sheet_name);
# ...
$worksheet->write($rowNum, $j,$_,$default_format);

after these steps I have some more lines in the same script:

my $Excel = Win32::OLE->GetActiveObject('Excel.Application')
    || Win32::OLE->new('Excel.Application');
$Excel->{'Visible'} = 0;    #0 is hidden, 1 is visible
$Excel->{DisplayAlerts}=1;  #0 is hide alerts

# Open File and Worksheet
my $return_file_name="C:\Users\admin\Desktop\Report_Gen\$file_name";
print ">>$return_file_name<<";
my $Book = $Excel->Workbooks->Open($return_file_name); # open Excel file
foreach my $Sheet (in $Book->Sheets) {
    my $LastCol = $Sheet->UsedRange->Find({What=>"*", 
        SearchDirection=>xlPrevious,
        SearchOrder=>xlByColumns})->{Column};    # mentioned error is from this line
    my $mylastcol = 'A';
    for (my $m=1;$m<$LastCol;$m++) {$mylastcol++;}
    my @columnheaders = ('A:'.$mylastcol);
    foreach my $range (@columnheaders){
        $Sheet->Columns($range)->AutoFit();
    }
How to&Answers:

I wrote a Perl script to convert a set of CSV files into spreadsheet format using Spreadsheet::WriteExcel. After some research I came to conclusion that there is no option to fix column width as Auto-fit option.

Autofit is a runtime option in Excel and so it isn’t possible to create it via the file format using Spreadsheet::WriteExcel.

However, the Spreadsheet::WriteExcel docs contain an example of how to simulate autofit with an explanation of some of the issues involved.