How to save Excel file in working directory in Win32::OLE

点点圈 提交于 2019-12-12 01:42:18

问题


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:


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;


来源:https://stackoverflow.com/questions/35501825/how-to-save-excel-file-in-working-directory-in-win32ole

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!