使用 Perl Excel 遍历单个列而不是每一列

Using Perl Excel to Loop Through A Single Column and Not Every Columns

我当前的 Perl 代码遍历 Excel 工作表中的每一行和每一列。

如果我在Excel中有3列数据,如何只循环遍历第2列来读取和写入特定数据?根据下面的数据输入,目标是将单元格从 Apples 更改为 Peaches。 下面是我的代码,代码下面有尝试的解决方案。我需要将第 2 列中的苹果替换为桃子,但苹果在第 1 列中保持不变。

注意:我回答了我自己的问题,但如果有人有更好的解决方案,那将是一个很好的学习教训。

输入:

  1           2           3
Grapes     Spinach     Mustard
Oranges    Apples      Ketchup
Apples     Potatoes    Horseradish

输出:

   1           2           3
Grapes     Spinach     Mustard
Oranges    Peaches     Ketchup
Apples     Potatoes    Horseradish

我的代码:

#! /usr/bin/perl
use v5.10.0;
use warnings;

use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::SaveParser;
use Spreadsheet::WriteExcel;

my $parser = Spreadsheet::ParseExcel::SaveParser->new();
my $workbook_R = $parser->parse('C:\Perl\databases\input.xls');

my $workbook_W = Spreadsheet::WriteExcel->new('C:\Perl\databases\output.xls');
my $worksheet_W = $workbook_W->add_worksheet();

for my $worksheet_R ($workbook_R->worksheets()) {

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

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

  my $value = $worksheet_R->get_cell($row, $col)->value;

# Testing if Apples Replace Peaches
  $value =~ s/Apples/Peaches/g;
  $worksheet_W->write($row, $col, $value);
  }
 }
}

我的一些解决方案是:

   1)        my $value = $worksheet_R->get_cell($row, 2)->value;
   2)        $worksheet_W->write($row, 2, $value);
   3)        for my $col ($col == 2 ) {

所有结果都是错误的数据输出。

对第 2 列和其他列使用 if/else 语句。

解决方法如下:

my $value = $worksheet_R->get_cell($row, $col)->value;

  if ($col ==1) {
# Apples Replace Peaches for ONLY Column 2
  $value =~ s/Apples/Peaches/g;
  $worksheet_W->write($row, $col, $value);
  }
    else {
      # Print the other data in other columns
      $worksheet_W->write($row, $col, $value);
  }