Excelでグラフの作成
Win32::OLEでExcelを操作してグラフを作成します。
Excelがインストールされている必要があります。
use strict;
use Win32::OLE;
use Win32::OLE::Const 'Microsoft Excel';
my $excel;
eval {
Win32::OLE->GetActiveObject('Excel.Application');
};
if ($@) {
die "Excelが入っていません。 $@";
}
unless (defined $excel) {
$excel = Win32::OLE->new('Excel.Application', '')
or die "Excelが起動できません。";
}
my $book = $excel->Workbooks->Add; # ワークシートの作成
my $sheet = $book->Worksheets(1);
make_data($sheet);
my $chart = $excel->Charts->Add;
make_chart($chart, $sheet);
$excel->{Visible} = 1;
exit;
# グラフの作成
sub make_chart {
my $chart = shift;
my $sheet = shift;
my $range = $sheet->Range($sheet->Cells(1, 1), $sheet->Cells(11, 4));
# グラフの元データ
$chart->SetSourceData({Source => $range, PlotBy => xlColumns});
# グラフタイプ
$chart->{ChartType} = xlColumnClustered;
# グラフタイトル
$chart->{HasTitle} = 1;
$chart->ChartTitle->{Name} = 'タイトル';
$chart->ChartTitle->Font->{Size} = 20;
# 凡例
$chart->{HasLegend} = 1;
# 軸の説明
my $cat = $chart->Axes(xlCategory, xlPrimary);
$cat->{HasTitle} = 1;
$cat->AxisTitle->{Text} = "番号";
$cat->AxisTitle->Font->{Size} = "20";
$cat->TickLabels->Font->{Size} = "10";
my $val = $chart->Axes(xlValue, xlPrimary);
$val->{HasTitle} = 1;
$val->AxisTitle->{Text} = "得点";
$val->AxisTitle->Font->{Size} = "20";
# 名称
$chart->{Name} = 'グラフサンプル';
}
# データの作成
sub make_data {
my $sheet = shift;
$sheet->Cells(1, 1)->{Value} = "番号";
$sheet->Cells(1, 2)->{Value} = "得点A";
$sheet->Cells(1, 3)->{Value} = "得点B";
$sheet->Cells(1, 4)->{Value} = "得点C";
foreach my $i (2 .. 11) {
$sheet->Cells($i, 1)->{Value} = "'".($i - 1);
$sheet->Cells($i, 2)->{Value} = int(rand 101);
$sheet->Cells($i, 3)->{Value} = int(rand 101);
$sheet->Cells($i, 4)->{Value} = int(rand 101);
}
}
