2014-11-05 64 views
1

我正在寫一個PERL代碼來從特定Excel工作表的特定行中選取值。我正在使用Spreadsheet :: ParseExcel模塊來達到此目的。我寫了這個代碼截至目前Spreadsheet :: ParseExcel在PERL查詢中

use Spreadsheet::ParseExcel::FmtDefault; 
use Spreadsheet::ParseExcel; 

     my $parser = Spreadsheet::ParseExcel->new(); 

     #my $name = <STDIN>; 
    die "You must provide a filename to $0 to be parsed as an Excel file" unless @ARGV; 
     my $workbook = $parser->parse($ARGV[0]); 
    my @values; 
     if (!defined $workbook) { 
     die $parser->error(), ".\n"; 
    } 

     for my $worksheet ($workbook->worksheets()) { 

     my ($row_min, $row_max) = $worksheet->row_range(); 
     my ($col_min, $col_max) = $worksheet->col_range(); 

     for my $row ($row_min .. $row_max) { 
      for my $col ($col_min .. $col_max) { 

       my $cell = $worksheet->get_cell($row, $col); 
       next unless $cell; 
       $cell->value(); 
      my $cell_type = $cell->{Type}; 
       if ($cell_type =~/Numeric/) 
       { 
       push @values, $cell->unformatted(); 
     } 
      } 
     } 
    } 

我能挑到一個特定的Excel工作表與該特定代碼的所有數值,但我想調整的代碼,以便它可以根據用戶需求在特定列中選取數值(例如:行B或行C中的所有數值)。我如何去調整我的代碼以使其成爲可能,或者是否有簡單的模塊可用,其中可以指定範圍(例如B2-B22)。任何幫助表示讚賞。

+0

所以你需要從第二個B行的列值至22行或在通用獲得價值弗羅馬特定列? – Praveen 2014-11-05 06:34:46

+0

@Praveen從用戶需要的特定列獲取值的通用代碼 – 2014-11-05 06:39:57

回答

1

請使用下面的perl代碼進行檢查。 Excel工作表行和列值以(0,0)開頭。因此,相應地分別輸入您的列和行號以獲得您想要的輸出。

代碼:

use strict; 
use warnings; 
use Spreadsheet::ParseXLSX; 

my $parser = Spreadsheet::ParseXLSX->new(); 
my $workbook = $parser->parse('C:\Users\Perl\test1.xls'); 

if (!defined $workbook) { 
die $parser->error(), ".\n"; 
    } 
my $worksheet = $workbook->worksheet(0); 
my ($row_min, $row_max) = $worksheet->row_range(); 
my ($col_min, $col_max) = $worksheet->col_range(); 

COLUMNS: print "Select the column number required from Excel\n"; 
my $column = <STDIN>; 
chomp($column); 
unless ($column =~/[0-9]+/){ 
print "Bummer!! Please Enter a number\n"; 
goto COLUMNS; 
} 

if($column gt $col_max){ 
    print "No such columns defined in the Excel"; 
    goto END; 
     } 

ROWS:print "Select number of rows required from column $column:\n"; 
my $rows = <STDIN>; 
chomp($rows); 
my $count = $rows+1; 
unless ($rows =~/[0-9]+/){ 
print "Bummer!! Please Enter a number\n"; 
goto ROWS; 
} 

    ROW_LABEL: if($rows le $row_max) 
    { 
    print "\nThe $count row values from column $column are:\n"; 
    for my $row ($row_min .. $rows) { 

     my $cell = $worksheet->get_cell($row, $column); 
     next unless $cell; 
     my $result = $cell->value();   
     print $result . "\n"; 
      } 
     } 
    else 
    { 
     $rows = $row_max; 
     goto ROW_LABEL ; 
     }  
END: 
相關問題