PERL查询中的Spreadsheet :: ParseExcel

时间:2014-11-05 06:29:10

标签: excel perl spreadsheet parseexcel

我正在编写PERL代码以从特定Excel工作表的特定行中选择值。我正在使用Spreadsheet :: ParseExcel模块来实现此目的。我现在已经编写了这段代码

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工作表中的所有数值,但我想调整代码,以便它可以根据用户需要在特定列中选取数值(例如:all行B或行C)中的数值。我如何调整我的代码以使其成为可能,或者是否有更简单的模块可用于指定范围(例如B2-B22)。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分: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: