473,396 Members | 2,129 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Open and create new Excel file with Perl and win32::OLE

Hello all, I am a new Perl programmer. Below is the beginnings of a code that I am using to manipulate an Excel spreadsheet via Perl using win32::OLE. However, what I'd like to do is the following: instead of either opening a file or creating a new one, I'd like to do BOTH. I was thinking of creating a loop where I could basically say something like:

if $excelfile exists, then open $excelfile, otherwise, create a new workbook named $excelfile

However, being new to Perl, I haven't quite been able to find the correct syntax. Can you provide any clues as to how to do this, or is it even possible?

Thanks! ;)

Expand|Select|Wrap|Line Numbers
  1.  ------------------------------------------------------------ 
  2. #!/usr/bin/perl -w
  3.  
  4. use strict;
  5. use Win32::OLE qw(in with);
  6. use Win32::OLE::Const 'Microsoft Excel';
  7.  
  8. $Win32::OLE::Warn = 3; # die on errors...
  9.  
  10. # get already active Excel application or open new
  11. my $Excel = Win32::OLE->GetActiveObject('Excel.Application')
  12. || Win32::OLE->new('Excel.Application', 'Quit'); 
  13.  
  14. my $excel_file = 'C:/Perl/myfolder/testbook';
  15.  
  16. # open Excel file
  17. my $Book = $Excel->Workbooks->Open("$excel_file"); 
  18. ------------------------------------------------------------
  19.  
Nov 18 '05 #1
3 41750
Niheel
2,460 Expert Mod 2GB
Hey,

You are almost there, all you need is the code for the if file exists / else:

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl -w
  2.  
  3. use strict;
  4. use Win32::OLE qw(in with);
  5. use Win32::OLE::Const 'Microsoft Excel';
  6.  
  7. $Win32::OLE::Warn = 3; # die on errors...
  8.  
  9. # get already active Excel application or open new
  10. my $Excel = Win32::OLE->GetActiveObject('Excel.Application')
  11. || Win32::OLE->new('Excel.Application', 'Quit'); 
  12.  
  13. my $excel_file = 'C:/Perl/myfolder/testbook';
  14.  
  15. // -e checks to see if the file exists
  16. if (-e "$excel_file")
  17. # open Excel file
  18. my $Book = $Excel->Workbooks->Open("$excel_file"); 
  19. # run any other excel code you want here
  20. # ...
  21. }else{
  22. // paste code here to create a new file 
  23. $excel->{Visible} = 1;
  24. $excel->{SheetsInNewWorkBook} = 1;
  25. $workbook = $excel->Workbooks->Add();
  26. $worksheet = $workbook->Worksheets(1);
  27. $worksheet->{Name} = "New WorkSheet";
  28.  
  29. # run any other excel code you want here
  30. # ...
  31.  
  32. $workbook->SaveAs($excel_file);
  33. }
  34.  
Nov 18 '05 #2
m3rajk
8
I had the same question. this was about link #40 hat i opened looking for help and the first one to go beyond giving mee how to open an excel file.

I have two more questions though:

1: how do i find the last row number with information so that I may jump to there?

2: how do i get this to actually fill in and save? when i run my script now it has 2 books with blank sheets.

my wrapper file (batch), with computer names removed for safety/brevity:
Expand|Select|Wrap|Line Numbers
  1. @echo on
  2. rem this batch is for cataloguing computers using two other "helpers"
  3. rem "helpers" are psinfo and compinfo
  4. rem information section is over, turning echo off.
  5. @echo off
  6.  
  7. compinfo -l l1.txt -c [a bunch of computer names] >> errlog.txt 
  8. compinfo -l l2.txt -c [a bunch of computer names] >> errlog.txt
  9.  
excerpt from my perl file that has the interesting parts of excel interaction

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use Getopt::Long; # used in getting unix-style options
  5. use Win32::OLE::Const 'Microsoft Excel'; # use OLE/Excel
  6. $Win32::OLE::Warn = 3; # die on errors...
  7.  
  8. # some stuff that's probably not interesting nor relevant
  9.  
  10. sub rep{
  11.   # this assumes two passed values,
  12.   # first a message
  13.   # second a flag for verbose (screen printing)
  14.   my $time=localtime().' | ';
  15.   print LOG "$time $_[0]\n";
  16.   if($_[1]){ print STDOUT "$time $_[0]\n"; }
  17. }
  18.  
  19. # stuff creating files of information used to create the excel spreadsheet
  20.  
  21. #######
  22. ## OLE interaction upon the saved files follows
  23. #######
  24.  
  25. # get an active Excel or create a new one
  26. my $Excel = Win32::OLE -> GetActiveObject('Excel.Application')
  27.   || Win32::OLE -> new('Excel.Application', 'Quit');
  28.  
  29. my $labrep="./Lab_Report_$date.xls";
  30.  
  31. # does the file exit?
  32. if(-e "$labrep"){
  33.   #we are just adding to it, so open it
  34.   my $report = $Excel->Workbooks->Open("$labrep");
  35.   my $ws = $report -> Worksheets(1);
  36.  
  37.   my $ldate = localtime();
  38.   &rep("Examining information gathered from lab computers @ $ldate\n", $verb);
  39.  
  40.   # start row counter
  41.   my $row=2;##<----bad! needs to jump to end!!!!!
  42.  
  43. ###
  44. #some stuff like below only without the first row and should be after what's there
  45. ###
  46.  
  47. }else{
  48.   # we have to create it, including make the first row
  49.   $Excel -> {'Visible'} = 1;
  50.   $Excel -> { 'SheetsInNewWorkBook' } = 1;
  51.   my $workbook = $Excel -> Workbooks -> Add();
  52.   my $ws = $workbook -> Worksheets(1);
  53.   $ws -> { 'Name' } = "Lab Report $date";
  54.  
  55.   # set first row titles
  56.   $ws -> Cells(1, "A") -> ('Value') = "Node";
  57.   $ws -> Cells(1, "B") -> ('Value') = "NAV";
  58.   $ws -> Cells(1, "C") -> ('Value') = "Alarms";
  59.   $ws -> Cells(1, "D") -> ('Value') = "SNMP";
  60.   $ws -> Cells(1, "E") -> ('Value') = "Uptime";
  61.   $ws -> Cells(1, "F") -> ('Value') = "Kernel Version";
  62.   $ws -> Cells(1, "G") -> ('Value') = "Product Type";
  63.   $ws -> Cells(1, "H") -> ('Value') = "Product Version";
  64.   $ws -> Cells(1, "I") -> ('Value') = "Service Pack";
  65.   $ws -> Cells(1, "J") -> ('Value') = "Kernel Build Number";
  66.   $ws -> Cells(1, "K") -> ('Value') = "Registered Organization";
  67.   $ws -> Cells(1, "L") -> ('Value') = "Registered Owner";
  68.   $ws -> Cells(1, "M") -> ('Value') = "Install Date";
  69.   $ws -> Cells(1, "N") -> ('Value') = "Activation Status";
  70.   $ws -> Cells(1, "O") -> ('Value') = "IE Version";
  71.   $ws -> Cells(1, "P") -> ('Value') = "System Root";
  72.   $ws -> Cells(1, "Q") -> ('Value') = "Processors";
  73.   $ws -> Cells(1, "R") -> ('Value') = "Processor Speed";
  74.   $ws -> Cells(1, "S") -> ('Value') = "Processor Type";
  75.   $ws -> Cells(1, "T") -> ('Value') = "Physical Memory";
  76.   $ws -> Cells(1, "U") -> ('Value') = "Installed OS Hotfixes";
  77.   $ws -> Cells(1, "V") -> ('Value') = "Other Applications";
  78.  
  79.   my $ldate = localtime();
  80.   &rep("Examining information gathered from lab computers @ $ldate\n", $verb);
  81.  
  82.   # start row counter
  83.   my $row=2;
  84.  
  85.   foreach my $node (@comps){
  86.     # for each node we check the information returned
  87.     # if there is no information we only have two items to place on the row,
  88.     # otherwise we have A-V items
  89.  
  90.     # set the first cell since that's always going to be the same
  91.     $ws -> Cells($row, "A") -> ('Value') = "$node";
  92.  
  93.     # try to open the file with the information
  94.     open LNINFO, "<$comp-$date.txt" or $err=1;
  95.  
  96.     if($err){
  97.       # there was an error on the file, so note that in the report
  98.       $ws -> Cells($row, "B") -> ('Value') =
  99.     "$comp-$date.txt could not be opened to be put into the lab report. $! $^E\n";
  100.  
  101.     }else{
  102.       # there was no error, so now we check the file,
  103.       # first reading in the file
  104.       my @examine;
  105.       while(<LNINFO>){
  106.     push @examine, $_;
  107.       }
  108.  
  109.       # then noting which couldnt be connected to
  110.       if($examine[6] =~ m/The network path was not found./i ){
  111.     $ws -> Cells($row, "B") -> ('Value') = "The network path was not found.";
  112.  
  113.       }else{
  114.     # we need to run through the file for the information to put into the rows
  115.  
  116.     # drop what's before what we need
  117.     while (!($examine[0] =~ m/Uptime.*/i)){ shift(@examine); }
  118.  
  119.     while (!($examine[0] =~ m/OS Hot Fix.*/i)){
  120.       # now go through a series of if/elsif sections for the rest
  121.       # hot fixes and programs will be handled slightly differently though
  122.  
  123.       if($examine[0] =~ m/Uptime:\s+(\w.*)/i){
  124.         $ws -> Cells($row, "E") -> ('Value') = "$1";
  125.       }elsif($examine[0] =~ m/Kernel version:\s+(\w.*)/i){
  126.         $ws -> Cells($row, "F") -> ('Value') = "$1";
  127.       }elsif($examine[0] =~ m/Product type:\s+(\w.*)/i){
  128.         $ws -> Cells($row, "G") -> ('Value') = "$1";
  129.       }elsif($examine[0] =~ m/Product version:\s+(\w.*)/i){
  130.         $ws -> Cells($row, "H") -> ('Value') = "$1";
  131.       }elsif($examine[0] =~ m/Service pack:\s+(\w.*)/i){
  132.         $ws -> Cells($row, "I") -> ('Value') = "$1";
  133.       }elsif($examine[0] =~ m/Kernel build number:\s+(\w.*)/i){
  134.         $ws -> Cells($row, "J") -> ('Value') = "$1";
  135.       }elsif($examine[0] =~ m/Registered organization:\s+(\w.*)/i){
  136.         $ws -> Cells($row, "K") -> ('Value') = "$1";
  137.       }elsif($examine[0] =~ m/Registered owner:\s+(\w.*)/i){
  138.         $ws -> Cells($row, "L") -> ('Value') = "$1";
  139.       }elsif($examine[0] =~ m/Install date:\s+(\w.*)/i){
  140.         $ws -> Cells($row, "M") -> ('Value') = "$1";
  141.       }elsif($examine[0] =~ m/Activation status:\s+(\w.*)/i){
  142.         $ws -> Cells($row, "N") -> ('Value') = "$1";
  143.       }elsif($examine[0] =~ m/IE version:\s+(\w.*)/i){
  144.         $ws -> Cells($row, "O") -> ('Value') = "$1";
  145.       }elsif($examine[0] =~ m/System root:\s+(\w.*)/i){
  146.         $ws -> Cells($row, "P") -> ('Value') = "$1";
  147.       }elsif($examine[0] =~ m/Processors:\s+(\w.*)/i){
  148.         $ws -> Cells($row, "Q") -> ('Value') = "$1";
  149.       }elsif($examine[0] =~ m/Processor speed:\s+(\w.*)/i){
  150.         $ws -> Cells($row, "R") -> ('Value') = "$1";
  151.       }elsif($examine[0] =~ m/Processor type:\s+(\w.*)/i){
  152.         $ws -> Cells($row, "S") -> ('Value') = "$1";
  153.       }elsif($examine[0] =~ m/Physical memory:\s+(\w.*)/i){
  154.         $ws -> Cells($row, "T") -> ('Value') = "$1";
  155.       }
  156.     }
  157.  
  158.     #  remove the line starting "OS Hot Fix..."
  159.     shift(@examine);
  160.     # create a variable for holding the hotfixes
  161.     my $hotfixes="\"";
  162.  
  163.     while (!($examine[0] =~ m/Applications.*/i)){
  164.       # while hot fixes need to be added. skip blank lines
  165.       if($examine[0] =~ m/\w/){
  166.         chomp($examine[0]);
  167.         $hotfixes .="$examine[0]\n";
  168.       }
  169.     }
  170.  
  171.     # add the hotfixes
  172.     $ws -> Cells($row, "U") -> ('Value') = "$hotfixes";
  173.  
  174.     #  remove the line starting "Applications..."
  175.     shift(@examine);
  176.  
  177.     my $apps='';
  178.     foreach my $app (@examine){
  179.       # the rest should all be applications to add
  180.       # so we're using a foreach to put them in
  181.       # only add lines that are not blank
  182.       # there are 3 special lines: NAV, Alarms, and SNMP
  183.       if($app =~ m/Symantec AntiVirus (\w+)/i){
  184.         $ws -> Cells($row, "B") -> ('Value') = "ver: $1";
  185.       }elsif($app =~ m/Alarm/i){
  186.         $ws -> Cells($row, "C") -> ('Value') = "Installed";
  187.       }elsif($app =~ m/SNMP Informant Agent \(([^\)]+)\) (\w.*)/i){
  188.         $ws -> Cells($row, "D") -> ('Value') = "$1 : $2";
  189.       }elsif($app =~ m/\s+(\w.*)/i){
  190.         $apps .= "$1\n";
  191.       }
  192.     }
  193.  
  194.     # add the other applications
  195.     $ws -> Cells($row, "V") -> ('Value') = "$apps";
  196.       }
  197.     }
  198.  
  199.     # end the loop increasing the row number
  200.     $row++;
  201.   }
  202.  
  203.   $workbook -> SaveAs($labrep); # save active sheet
  204. }
  205.  
  206. # save and exit
  207. $Excel -> Workbooks -> Save(); # save file
  208. $Excel -> Workbooks -> Quit(); # leave excel
  209. my $et=locatime();
  210. &rep("program completed at $et.",$verb); # wrap up log
  211. close LOG; # close log
  212.  
the script "finishes" but i never get the completed line in the log file, nor does the excel have any information, nor is there anything in the errlog.txt file.

the reg log only has the print out i would expect showing one how far the script is.
Mar 8 '06 #3
poolboi
170 100+
hi,
just came across this thread thought u might help me out
i tried to do it yr way..
but when i created a file already
it should input a hi at the position i stated
but it didn't...
is there anything wrong with my code?

Expand|Select|Wrap|Line Numbers
  1. use Win32::OLE;
  2.  
  3.         # use existing instance if Excel is already running
  4.         eval {$ex = Win32::OLE->GetActiveObject('Excel.Application')};
  5.         die "Excel not installed" if $@;
  6.         unless (defined $ex) {
  7.             $ex = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;})
  8.                     or die "Oops, cannot start Excel";
  9.         }
  10.  
  11.     if (-e "C:\\Documents and Settings\\clong\\Desktop\\perl\\$save_file_name.xls")
  12.  
  13.     {$book = $ex->Workbooks->Open("C:\\Documents and Settings\\clong\\Desktop\\perl\\$save_file_name.xls");
  14.     $sheet->Cells(3,1)->{Value} = ['hi'];
  15.  
  16.     }else{
  17.  
  18.         # get a new workbook
  19.         $book = $ex->Workbooks->Add;
  20.     $sheet = $book->Worksheets(1);
  21.  
  22.         # write a 2 rows by 3 columns range
  23.  
  24.         $sheet->Range("A1:J2")->{Value} = [['Date','Total (IN)','Succ (IN)','Pk (IN)/Hrs','Pk (OUT)/Hrs','Peak Hour','Total (OUT)','Succ (OUT)','MO(IN)','MO(OUT)'],
  25.                                            [$date, $total_in, $succ_in,$pk_in,$pk_out,"$pk_hour - $pk_hour_dur hr",$total_out,$succ_out ]];
  26.  
  27.  
  28.     $sheet->Range("K1:L2")->{Value} = [['Pk Msg/sec','Max Pk Msg/sec'],
  29.                       [$max_pk_msg,$pk_msg]];
  30.  
  31.  
  32.     foreach(@parameters)
  33.     {
  34.     $sheet->Cells(2,9)->{Value} = [$parameter_in_array{$_}];
  35.     $sheet->Cells(2,10)->{Value} = [$parameter_out_array{$_}];
  36.     }
  37.  
  38.  
  39.          # print "XyzzyPerl"
  40.         $array = $sheet->Range("A3:I1")->{Value};
  41.         for (@$array) {
  42.             for (@$_) {
  43.                 print defined($_) ? "$_|" : "<undef>|";
  44.             }
  45.             print "\n";
  46.         }
  47.  
  48.         # save and exit
  49.  
  50.         $book->SaveAs ("C:\\Documents and Settings\\clong\\Desktop\\perl\\$save_file_name.xls") ;
  51.         undef $book;
  52.         undef $ex;
  53.     }
  54.  
Jan 29 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Luis Ferrao | last post by:
Hi, My Windows Forms application uses the WebBrowser control to open an Excel file since OLE objects are gone in .Net. The application is actualy a clone of the one found in the MS Knowledge...
2
by: JBAdamsJr | last post by:
I want to be able to create an Excel file with a VB.NET program on a server that does not have Microsoft Excel loaded on it. I am using the Jet OLE DB to read other data files. Can this be used to...
0
by: shaurya.rastogi | last post by:
I need to open an Excel file that has been stored in the Access Database using the insert Object functionality of MSAccess manually. What i am aware of is that i cant just read the field...
0
by: shaurya | last post by:
I need to open an Excel file that has been stored in the Access Database using the insert Object functionality of MSAccess manually. What i am aware of is that i cant just read the field...
1
by: marle | last post by:
Hi all, Can anyone briefly explain how to Open an excel file using OLE? marle..
0
by: shintu | last post by:
Hallo, I am trying to write french accented characters é è ê in Excel worksheet using my perl script , But I am stuck here as I couldnt find a way of writing it !: My code: use strict;...
1
by: mohanprasadgutta | last post by:
Hi, I need help to open a password protected excel file in perl using Win32:OLE. when I tried to open file in normal way at the time of program execution it is prompting me to enter password. I am...
6
by: poolboi | last post by:
hi all, i've got the following program that needs yr help: use Win32::OLE; # use existing instance if Excel is already running eval {$ex =...
13
by: Prasanna CRN | last post by:
I am a Perl Programmer & i am using WIN32::OLE for Excel operations. I wanted to use conditional formulas like 'if' in excel via Perl. Thanks in Advance.
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.