in reply to Re^6: Reading Excel
in thread Reading Excel

Run this to create a known good xlsm file before then opening and reading it.

#!perl use strict; use warnings; use Win32::OLE; use Data::Dump 'pp'; $Win32::OLE::Warn = 3; # get already active Excel application or open new my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application', 'Quit'); # create macro enabled workbook my $excelfile = "C:\\perlpractice\\testfile.xlsm"; my $range = 'B1:E40'; my $top_left = create_xlsm($excelfile,$range); my $Book = $Excel->Workbooks->Open($excelfile); # open Excel file # Read spreadsheet my $Sheet = $Book->Worksheets(1); my $array = $Sheet->Range($range)->{'Value'}; print "$top_left = ".$array->[0][0]."\n"; pp $array; $Book->Close; sub create_xlsm { my ($file,$range) = @_; my ($start,$end) = split ':',$range; my $Book = $Excel->Workbooks->Add(); # new Excel file my $Sheet = $Book->Worksheets(1); my $rng = $Sheet->Range($range); my $cols = $rng->{'Columns'}->Count; my $rows = $rng->{'Rows'}->Count; #print "$rows $cols\n"; my @data=(); for my $c (0..$cols-1){ for my $r ( 0..$rows-1 ){ $data[$r][$c] = $r.'_'.$c; } } $rng->{'NumberFormat'} = '@'; $rng->{'Value'} = \@data; $Sheet->Range($start)->{'Value'} = scalar localtime; # top left $Book->SaveAs({ Filename=>$file, FileFormat=>52 }); #xlsm $Book->Close; undef $Book; return $start; }
Updated : removed hard coded range
poj

Replies are listed 'Best First'.
Re^8: Reading Excel
by ravi179 (Novice) on Jan 30, 2017 at 04:45 UTC

    my data starts from B1.If i am running the below script it is showing can't call method worksheets o an undefined value.

    use Win32::OLE qw(in with); use Win32::OLE::Const 'Microsoft Excel'; $Win32::OLE::Warn = 3; my $Excel=Win32::OLE->GetActiveObject('Excel.Application') $excelfile= "C:/perlpractice/simple.xlsm"; $Book=$Excel->Workbooks->Open($excelfile); $Sheet=$Book->Worksheets(1);

      After fixing your bugs this works for me

      use Win32::OLE qw(in with); use Win32::OLE::Const 'Microsoft Excel'; $Win32::OLE::Warn = 3; #my $Excel=Win32::OLE->GetActiveObject('Excel.Application') my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application', 'Quit'); #$excelfile= "C:/perlpractice/simple.xlsm"; $excelfile= "C:/perlpractice/testfile.xlsm"; $Book=$Excel->Workbooks->Open($excelfile); $Sheet=$Book->Worksheets(1);

        Thankyou.But if iam running the same script OLE exception fro m "Microsoft Excel"; Unable to get the Open property of the Workbook class.Win32::OLE (0.1709)error 0x800a03ec in METHOD/PROPERTYGET "Open" at C:\Perl\Read.pl