みんな大好き Excel ファイルを perl で書くメモ。
数字を 3 桁毎にカンマで区切って表示する方法。
add_format に num_format を設定する。こんな感じに。
フォーマットは Excel のユーザ定義を参照。
my $format1 = $book->add_format(
font => $font_name,
size => $font_size,
bold => 1,
border => 1,
valign => 'vcenter',
align => 'right',
num_format => '#,##0'
);
追記したソース。
#!/usr/bin/perl
use strict;
use warnings;
use Spreadsheet::WriteExcel;
my $file = "dir/perl.xls";
my $font_name = 'MS UI Gothic';
my $font_size = '11';
my $book = Spreadsheet::WriteExcel->new("$file");
my $sheet = $book->add_worksheet();
my $format0 = $book->add_format(
font => $font_name,
size => $font_size,
bold => 1,
border => 1,
valign => 'vcenter',
align => 'center'
);
my $format1 = $book->add_format(
font => $font_name,
size => $font_size,
bold => 1,
border => 1,
valign => 'vcenter',
align => 'right',
num_format => '#,##0'
);
my $x = '0';
my $y = '0';
$sheet->merge_range( $x, $y, $x, $y + 5, "write start", $format0 );
$x++;
for (my $i = '0'; $i <= '5'; $i++ ) {
for (my $j = '1'; $j <= '20'; $j++ ) {
$sheet->write( $x, $y + $i, int( rand(5000) ), $format1 );
$x++;
if ( $j == '20' ) {
my $abc = &column_abc( $y + $i );
my $range = $abc . ($x - $j) . ":" . $abc . $x;
my $excel_func = "=SUM($range)";
$sheet->write( $x, $y + $i, $excel_func, $format1 );
}
}
$x = '1';
}
$book->close();
sub column_abc {
my $position = shift;
my @abc = ( 'A'..'Z' );
my ( $abc, $i, $j );
if ( $position > '701' ) {
$abc = "over";
} elsif ( $position > '51' ) {
$i = int( $position / 26 ) - 1;
$j = $position - ( $i + 1 ) * 26;
$abc = "$abc[$i]$abc[$j]";
} elsif ( $position > '25' ) {
$i = int( $position / 26 ) - 1;
$j = $position - 26;
$abc = "$abc[$i]$abc[$j]";
} else {
$i = $position;
$abc = "$abc[$i]";
}
return( $abc );
}
exit;
これを実行するとこんなやつができます。
数値は +/- どちらでもこの方法で対応できます。
