我正在构建一个PERL脚本来搜索和替换EXCEL单元A1。我的代码有错误,它将在输入文件中找到“ Apples”,但不会在输出文件中用“ Peaches”替换“ Apples”。
我有一个XLS EXCEL INPUT文件(file_in.xls),其内容显示如下:
A---------------B
-----------------------
1 Apples | Carrots
-----------------------
2 Oranges | Spinach
-----------------------
3 Grapes | Celery
-----------------------
我需要对EXCEL输出文件(file_out.xls)的单元格(A1)中的苹果进行搜索/替换,以获取桃子。
A----------------B
-----------------------
1 Peaches | Carrots
-----------------------
2 Oranges | Spinach
-----------------------
3 Grapes | Celery
-----------------------
这是Perl代码:
use v5.10.0;
use warnings;
use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::SaveParser;
use Spreadsheet::WriteExcel;
my $parser = Spreadsheet::ParseExcel::SaveParser->new();
my $file1 = $parser->Parse("C:/Perl/scripts/file_in.xls");
my $workbook_R = $parser->parse('file_in.xls');
my $workbook_W = Spreadsheet::WriteExcel->new('C:\Perl\scripts\file_out.xls');
my $worksheet_W = $workbook_W->add_worksheet();
my $sheet = ${ $file1->{Worksheet_R} }[0];
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 $cell = $worksheet_R->get_cell( $row, $col );
next unless $cell;
if($cell->value() =~ /Apples/) {
$worksheet_R->write($cell,"Oranges");}
}
}
}
答案 0 :(得分:3)
您的代码有两个问题:
$worksheet_W
您不会写出其中没有Apples
的单元格的内容。
for my $row ( $row_min .. $row_max ) {
for my $col ( $col_min .. $col_max ) {
my $cell = $worksheet_R->get_cell( $row, $col );
// if the cell contains Apples, write 'Peaches' instead
if($cell->value() =~ /Apples/) {
$worksheet_W->write($row, $col,"Peaches");
}
else {
// print the existing cell contents
$worksheet_W->write($row, $col, $cell);
}
}
}