如何选择与excel中特定变量匹配的特定行?

时间:2014-10-31 02:13:48

标签: excel perl

我得到了存储在数组中的变量列表。我知道如何选择特定的列和行,但我只想选择匹配数组中变量的特定行(假设所有变量都是唯一的,只会出现在excel中一次)。有可能做到这一点以及如何做到这一点?

Excel中:

Name    Code    Age
John    0123    18
ean     1234    19

我现在的代码:

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

@name = ("john", "tommy", "ming", "ean");

##Loop through the array and search in excel##
foreach my $test (@name) {

my $parser   = Spreadsheet::ParseXLSX->new();
my $workbook = $parser->parse('C:\namelist.xlsx');

if ( !defined $workbook ) {
    die $parser->error(), ".\n";
}

for my $worksheet ( $workbook->worksheets('Name List') ) {

    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 ) {

           **Any Idea what should I do here to get expected result?**

            }
        }
    }
 }

预期结果:循环遍历数组@name时,它将在excel中搜索,如果匹配John之类的变量,它将检索该行的所有数据并将其存储在变量中。例如。 $code = 01234;$Age=18;

任何相关的帖子/信息/ ans要分享,因为我找不到。谢谢!

1 个答案:

答案 0 :(得分:2)

尝试在perl中使用以下代码:

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

my $parser   = Spreadsheet::ParseXLSX->new();
my $workbook = $parser->parse('C:\namelist.xlsx');

if ( !defined $workbook ) {
 die $parser->error(), ".\n";
     }

my @name = ("john", "tommy", "ming", "ean");   
for my $worksheet ( $workbook->worksheets('Name List') ) {

    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;

        foreach my $result (@name)
          {
            my $string = $cell->value();
             if($result =~ m/$string/i)
               {  
                    my $codeCell = $worksheet->get_cell($row,1);
                    my $ageCell  = $worksheet->get_cell($row,2);
                    print "Name : $string\t";
                   if(defined $codeCell and $codeCell->value() ne "")
                     {
                          my $code = $codeCell->value(); 
                        print "Code : $code\t"; 
                        }
                    if(defined $ageCell and $ageCell->value() ne "")
                     {
                          my $age = $ageCell->value(); 
                        print "Age : $age\n"; 
                        }                
                  }

              }
          }
       }
   }