Home » excel » excel – perl: save workbook with Win32::OLE not possible

excel – perl: save workbook with Win32::OLE not possible

Posted by: admin May 14, 2020 Leave a comment


I’ve following simplified script (i’m not able to change the Win32:OLE)

use warnings;
use strict;
use Cwd;
use Win32::OLE;   
use Win32::OLE::Const 'Microsoft Excel';

my $excel = Win32::OLE->new('Excel.Application');
my $workbook = $excel->Workbooks->Add;
my $worksheet   = $workbook->Worksheets(1);
$worksheet->Range("B1")->{Value} ="Hello";
$worksheet->Range("C2")->{Value} ="World";
# Get current directory using Cwd.pm

my $saveTo = cwd();
$saveTo = $saveTo . '/HelloWorld.xls';
print "$saveTo\n";
undef $workbook;

And it will produce the following output:


So i assume the save path is right. But it won’t create a file. If i add $workbook->Close(); its at least asking to close the workbook. but this is all.

While $workbook->SaveAs("HelloWorld.xls"); is saving my workbook to “MyDocuments\HelloWorld.xls” with the right content.

How to i get this xls written to my cwd() dir, like its written to my documents?

(Enviroment: Windows 7 64bit, Perl: (v5.16.1) built for MSWin32-x64-multi-thread)

How to&Answers:

Since this is running on Windows, you need to replace the slashes with backslashes in $saveTo. Add a line like

$saveTo =~ s/\//\/g;

before the call to $workbook->SaveAs().