473,763 Members | 7,719 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

1 New Member
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 41787
Niheel
2,456 Recognized Expert Moderator Top Contributor
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 New Member
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 New Member
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
6440
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 Base Article "How to Use the WebBrowser Control to Open Office Documents with Visual C# .NET" which can be found here: http://support.microsoft.com/default.aspx?scid=kb;EN-US;304662 The application does what it's supposed to (ie Loads embeded Excel
2
7281
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 save an array in an Excel .XLS format?
0
1951
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 containing the Excel File into a Byte Array and pass it to the Excel object in C#,as the file is wrapped in the OLE Wrapper used by Access while inserting the file in database. I have tried locating the Header of Excel file from the byte array and...
0
1388
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 containing the Excel File into a Byte Array and pass it to the Excel object in C#,as the file is wrapped in the OLE Wrapper used by Access while inserting the file in database . I have tried locating the Header of Excel file from the byte array and read...
1
2132
by: marle | last post by:
Hi all, Can anyone briefly explain how to Open an excel file using OLE? marle..
0
2301
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; use warnings;
1
6207
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 giving the script i used for opening excel file.. So i want to know how to provide password parameter while opening the file. use strict; use Win32::OLE; use Win32::OLE::Const 'Microsoft Excel'; use Win32::OLE::Variant qw(:DEFAULT nothing);
6
6480
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 = Win32::OLE->GetActiveObject('Excel.Application')}; die "Excel not installed" if $@; unless (defined $ex) {
13
4689
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
9563
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9822
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8821
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7366
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3522
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2793
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.