使用Perl Excel循环通过单列而不是每列

问题描述 投票:0回答:1

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

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

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

INPUT:

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

OUTPUT:

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

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

excel perl xls
1个回答
0
投票

对列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);
  }
© www.soinside.com 2019 - 2024. All rights reserved.