Home » excel » Proper spreadsheet build with Excel::Writer::XLSX in perl

Proper spreadsheet build with Excel::Writer::XLSX in perl

Posted by: admin May 14, 2020 Leave a comment

Questions:

Being a new perl user, it’s hard to understand everything with not much experience.

Bellow is a portion of a perl script which is supposed to build a spreadsheet from parsing a text file generated by a custom software . After execution, the xlsx is built by perl, the product group is populated in each row of the designated column, and the product is inserted in the next column. When I have too many products they end up being inserted in the next column, and the next column, and on and on, of the given group.
Ideally I would like to have the multiple products inserted in the next row of the same products column.

Currently:

==========================

Group | Product_1 | Prodcut_2 |

===========================

Ideally:

==================

Group | Product1 |

==================

(blank) | Product2 |

==================

(blank) | Product3 |

==================

How would this be accomplished?

Below is a snippet of the current code:

    my $product_regex ='^Newly listed product: (.*)$';
    if ($line =~ /$product_regex/) {
            $change = $1;

            if ($some_flag == 1) {
                    $some_flag = 0;
                    push(@{ $product_changes{$group}  } , $change);
            }
    }


my $format = $workbook->add_format();
$format->set_text_wrap();
my $worksheet = $workbook->add_worksheet( 'Sheet1' );
# Writing 2 column headers
$worksheet->write( 0, 0, 'Group' );
$worksheet->write( 0, 1, 'Product' );
my $row;
$row = 1;
for my $key (sort keys %product_changes) {
    # To avoid evaluation from Excel, $key must be placed in quotes
    $worksheet->write($row, 0, $key, $format );
    $worksheet->write($row, 1, $product_changes{"$key"},$format );
    $row++;
How to&Answers:

Not sure if you are looking for help in parsing, or writing the output.

Here is a way to write the output, assuming you have it parsed into a hash of arrayrefs, group => [ product_change, product_change, ...]

my $row = 1;
for my $key (sort keys %product_changes) {
    $worksheet->write($row, 0, $key, $format);
    for my $pc (@{$product_changes{"$key"}}) {
        $worksheet->write($row++, 1, $pc, $format);
    }
}