How to save Excel file in working directory in Win

2019-09-10 06:31发布

I am trying to parse an Excel file in perl. After I extract the required info from it, I close the Excel file. At the end I am trying to save a new Excel file with a different name in the same directory. But this Excel is getting stored in 'My Documents' folder.

use Storable ;
use Cwd;

use Win32::OLE ;
use Win32::OLE qw(in with) ;
use Win32::OLE in ;
use Win32::OLE::Const 'Microsoft Excel';

use Excel::Writer::XLSX;

my $Excel = Win32::OLE->new("Excel.Application");
my $excel = $Excel->Workbooks->Add();

my $sheet = $excel->Worksheets(1);
$sheet->Activate();

my $new_file = "Temp_file.xlsm";
my $new_excel = cwd.'\\'.$new_file;
$new_excel =~ s/\//\\/g;

$excel->SaveAs($new_excel);

$Excel->{DisplayAlerts} = 0;
$excel->{Saved} = 1;
$excel->Close;

1条回答
聊天终结者
2楼-- · 2019-09-10 07:11

Here is an update based on your code. First, you are letting Win32::OLE errors to be silently ignored. Instead, set: $Win32::OLE::Warn = 3 so it croaks whenever something goes wrong. Second, the way you try to obtain an Excel.Application instance is not correct. For one thing, if something goes wrong, you will have instances of Excel will remain floating around.

You are also confusing an Excel instance, a workbook, and the sheets it contains. If you did have $Win32::OLE::Warn = 3, you would have received a notification of where things are going wrong.

You should also always have use strict and use warnings in your script. Others will be more inclined to try to help if they know your problem is not caused by some trivial typo.

You also don't need three separate use Win32::OLE statements.

The code below "works". Compare it to yours.

Finally, if you are manipulating your sheet via Win32::OLE, there is no reason to have Excel::Writer::XLSX in your code.

use feature 'say';
use strict;
use warnings;

use File::Spec::Functions qw( rel2abs );
use Win32::OLE qw(in with) ;
use Win32::OLE::Const 'Microsoft Excel';
$Win32::OLE::Warn = 3;

my $excel = eval {
        Win32::OLE->GetActiveObject('Excel.Application');
    } || Win32::OLE->new('Excel.Application', sub { $_[0]->Quit });

my $wb = $excel->Workbooks->Add;
my $sheet = $wb->Worksheets->Add;

$wb->SaveAs( rel2abs('temp_file.xlsm') );

$excel->{DisplayAlerts} = 0;
$wb->{Saved} = 1;
$wb->Close;
查看更多
登录 后发表回答