#!/usr/bin/perl use strict; use warnings; use Spreadsheet::WriteExcel(); my $book = Spreadsheet::WriteExcel->new('example.xls') or die "Couldn't create spreadsheet : $!"; my $bold = $book->add_format(); $bold->set_bold(); ## Create an anonymous sub for writing to a new worksheet my $writer = make_writer($book->add_worksheet('Example sheet')); my @months = qw (Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); $writer->( 'write', $_, $bold ) for ('Year',@months); $writer->('next_row'); my $val = 0; for my $year (2003..2007 ) { $writer->('write',$year); for (1..@months) { $writer->( 'write', $val ); $val = $val + 50; } $writer->('next_row'); } $writer->('set_col_widths'); $book->close or die "Couldn't close spreadsheet : $!"; #=================================== sub make_writer { #=================================== ## These lexical variables will be remembered inside the anonymous sub my $sheet = shift; my $col = 0; my $row = 0; my @max_col_width; return sub { my $action = shift; ## Write to the current cell and move to the next cell if ( $action eq 'write' ) { my ( $value, $format ) = @_; ## Set the max_col_width my $width = length($value); $max_col_width[$col] = $width if !defined $max_col_width[$col] || $width > $max_col_width[$col]; $sheet->write( $row, $col, $value, $format ); return $col++; } ## Move to the beginning of the next row elsif ( $action eq 'next_row' ) { $row++; my $orig_col = $col; $col = 0; return $orig_col; } ## Set the column widths to the width of the widest value elsif ( $action eq 'set_col_widths' ) { for ( my $col = 0; $col < @max_col_width; $col++ ) { $sheet->set_column( $col, $col, $max_col_width[$col] ); } return; } $action ||= ''; die "Unknown action '$action'"; }; }