如何遍历特定列并检索特定行 - Excel

时间:2014-11-10 03:52:49

标签: excel perl

我学会了如何通过指向特定列来检索特定值。但现在我想学习如何通过特定列循环(循环遍历数组),如果匹配特定变量(来自数组),它将检索特定列并将其打印出来。

Excel中

Column1 Column2 Column3 Column4 Column5            Column6
1        2700K    80      NA    L130-2780003000W21 T3C27821L-01BA
2        3000K    80      NA    L130-3080003000W21 T3C30821L-01BA
3        3500K    80      NA    L130-3580003000W21 T3C35821L-01BA
4        4000K    80      NA    L130-4080003000W21 T3C40821L-01BA
5        5000K    80      NA    L130-5080003000W21 T3C50821L-01BA
6        5700K    80      NA    L130-5780003000W21 T3C57821L-01BA
7        6500K    80      NA    L130-6580003000W21 T3C65821L-01BA
8        2200K    80      NA    L130-2280002011001 T3422811L-01BA

当前代码

use strict;
use warnings;
use Spreadsheet::ParseXLSX;
my $parser   = Spreadsheet::ParseXLSX->new();
my $workbook = $parser->parse('C:\testing\parts.xlsx');

 if ( !defined $workbook ) {
    die $parser->error(), ".\n";
}
# Array
my @list = ();

@list = ("T3C27821L-01BA","T3C35821L-01BA","T3C50821L-01BA","T3C65821L-01BA");

my $worksheet = ($workbook->worksheet('Sheet 1'));
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 ) {
        # Here will loop through the Column6 and retrieve
        # specific columns if matched(array matched Column6).
        foreach my $parts (@list) {
            # If matched, retrieve Column 2, Column 3, Column 5.
            # Here will print out the variable (from array) and
            # the columns that retrieved.
            print "Parts - $parts, $Column2, $Column3, Column5";
        }
    }
}

预期 - 使用@list数组中的变量列表并循环浏览Column6,如果匹配则检索特定列,Column2Column3Column5和打印出来。

感谢您的教学!

1 个答案:

答案 0 :(得分:1)

看看Spreadsheet::ParseExcel。他们的概要包含以下代码示例,可以帮助您入门。 :)

use strict;
use Spreadsheet::ParseExcel;

my $parser   = Spreadsheet::ParseExcel->new();
my $workbook = $parser->parse('Book1.xls');

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;

            print "Row, Col    = ($row, $col)\n";
            print "Value       = ", $cell->value(),       "\n";
            print "Unformatted = ", $cell->unformatted(), "\n";
            print "\n";
        }
    }
}

要将单元格与值进行比较,您可以使用Perl的正则表达式匹配。

if($cell->value() =~ /2700K/) {
    print "Cell found!";
}

干杯, MrMcKizzle