I'm assuming you have an existing spreadsheet which you need to update and write to a new file. I have two generic subroutines I use to read/write Excel files. I would do it this way:
- Read in all rows from existing file
- Update the rows
- Write the updated rows to new file
use strict;
use warnings;
use Spreadsheet::ParseXLSX;
use Excel::Writer::XLSX;
my $in_file = "SRC185.xlsx";
my $out_file = "Output2022.xlsx";
# Read in all rows from existing file
my $rows = read_excel($in_file);
my $headers = [
"source_id",
"first_name",
"middle",
"last_name",
"address1",
"city",
"state",
"postal_code",
"phone_number",
"address3",
"province",
"email",
];
my $CA_zip = 90005;
# Update the rows
for my $row (@$rows) {
if ($row->[6] eq 'CA' && ! $row->[7]) {
$row->[7] = $CA_zip;
}
}
# add headers as first row
unshift(@$rows, $headers);
# Write the updated rows to new file
my $col_num = scalar @$headers - 1;
write_excel($out_file, $rows, $col_num);
sub read_excel {
my ( $file, $sheet ) = @_;
$sheet ||= 0;
my $parser = Spreadsheet::ParseXLSX->new();
my $workbook = $parser->parse($file);
if ( not defined $workbook ) {
die $parser->error;
}
my $worksheet = $workbook->worksheet($sheet);
my ( $row_min, $row_max ) = $worksheet->row_range();
my ( $col_min, $col_max ) = $worksheet->col_range();
my @rows;
for my $row ( $row_min .. $row_max ) {
my @cells;
for my $col ( $col_min .. $col_max ) {
my $cell = $worksheet->get_cell( $row, $col );
if (not $cell) {
push(@cells,'');
next;
}
my $value = $cell->value();
push(@cells,$value);
}
push(@rows,\@cells);
}
return \@rows;
}
sub write_excel {
my ( $file, $rows, $col_max ) = @_;
my $workbook = Excel::Writer::XLSX->new( $file );
if ( not defined $workbook ) {
die "Could not open file: $!";
}
my $worksheet = $workbook->add_worksheet();
my $row_num = 0;
for my $row ( @$rows ) {
for my $col (0 .. $col_max) {
$worksheet->write( $row_num, $col, $row->[$col] );
}
$row_num++;
}
$workbook->close();
return;
}