Home » excel » windows – How can one open Excel (the program, not a file) from a perl program?

windows – How can one open Excel (the program, not a file) from a perl program?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I currently have a perl program in Windows that creates and populates an excel file via Spreadsheet::WriteExcel, but I’d like to have that file opened as my program closes. I tried googling for information, but all I found was how to open and read excel files within perl. Would anyone be able to help me?

How to&Answers:

I recommend this:

`your_file.xls`;

It just executes a system command. Assuming Excel files are set to default open with Excel, this will work (adding the full path to the file may or may not be necessary, depending on your setup).

Other options:

system("your_file.xls");
`C:\Program Files\...\excel.exe your_file.xls`;
system("C:\Program Files\...\excel.exe your_file.xls");

Answer:

I would use Win32::OLE for this. OLE is the Office extensions that you can use to perform tasks with the applications. This example should work (I haven’t tested it):

use strict;
use warnings;
use Win32::OLE;
use Win32::OLE::Const 'Microsoft Excel';
my $excel = Win32::OLE->GetActiveObject('Excel.Application')
  || Win32::OLE->new( 'Excel.Application', 'Quit' );
$excel->{Visible} = 1;

If you end up going down this route, here’s a reference to the Excel 2007 commands.

Answer:

The following works for me. It does not require using any additional module(s).

system "start excel $file";

Answer:

you can use the exec command in Perl like this:

my $excel_file = "file.xlsx";
exec "cmd", "/c", "start", $excel_file;

This will open the default program in your system to open xlsx files.
I like this option because if the user does not have excel installed, only libreoffice (for example), the system will open the file with libreoffice.