OK, I've created a PivotChart manually in Excel and I now understand what you are trying to achieve. I don't believe it is possible to create that special type of chart with Excel::Writer::XLSX. If you are using Windows then it can be done with Win32::OLE. For example
#!/usr/bin/perl
use strict;
use Win32::OLE 'in';
use Win32::OLE::Const 'Microsoft Excel';
$Win32::OLE::Warn = 3; # Die on Errors.
printf "Win32:OLE Version %s\n",$Win32::OLE::VERSION;
# Create new book
my $dir = 'c:\\temp\\';
my $file = 'chart.xlsx';
my $Excel = Win32::OLE->GetActiveObject('Excel.Application')
|| Win32::OLE->new('Excel.Application', 'Quit');
$Excel->{DisplayAlerts} = 0;
$Excel->{Visible} = 1;
my $Book = $Excel->Workbooks->Add();
printf "Created $file with %s sheets\n",$Book->sheets->Count;;
my $Sheet1 = $Book->Worksheets('Sheet1');
my $Sheet2 = $Book->Worksheets('Sheet2');
setup($Sheet1, 1500); #test data
# create PivotTable
my $range1 = $Sheet1->UsedRange->{'Address'};
print "Data Range = $range1\n";
my $cache = $Book->{'PivotCaches'}->create(
{
SourceType => xlDatabase,
SourceData => $range1,
Version => xlPivotTableVersion14,
} );
my $pvt = $cache->createPivotTable(
{
TableDestination => "Sheet2!R1C1",
TableName => "PivotTable1",
DefaultVersion => xlPivotTableVersion14,
} );
$pvt->addDataField(
$pvt->PivotFields('User Id'),
"Count of User ID",
xlCount
);
$pvt->PivotFields("Application Name")->{Orientation} = xlColumnField;
$pvt->PivotFields("Device")->{Orientation} = xlRowField;
$pvt->PivotFields("Browser")->{Orientation} = xlRowField;
# create PivotChart
$Sheet2->{'Shapes'}->AddChart();
my $shape = $Sheet2->Shapes('Chart 1');
$shape->ScaleWidth(2,0);
$shape->ScaleHeight(2,0);
my $chart = $shape->Chart;
$chart->{HasTitle} = 1;
$chart->{ChartTitle}->{Text} = "PivotChart Created ".scalar localtime;
$chart->{ChartType} = xlColumnClustered;
my $range2 = $Sheet2->UsedRange;
printf "Chart Range = %s\n",$range2->{'Address'};
$chart->SetSourceData({ Source => $range2 });
# save new workbook
$Book->{'ShowPivotTableFieldList'} = 0;
$Book->SaveAs({'Filename' => $dir.$file});
print "Chart is on Sheet2\n";
$Excel->Quit;
#system ( "excel $dir$file" );
# random test data generator
sub setup {
my ($sheet,$max) = @_;
my @dev = ('Computer','Mobile','Tablet');
my @bro = ('IE11','Chrome','Firefox','Safari');
my @app = ('AppA','AppB','AppC','AppD','AppE');
my $col = 1;
for ('User Id','User Display Name','User Email Id','Device',
'Browser','Application Name','Timestamp'){
$sheet->Cells(1,$col)->{'Value'} = $_;
++$col;
}
my $row = 2;
for (1..$max){
$sheet->Cells($row,1)->{'Value'} = "User $_";
$sheet->Cells($row,4)->{'Value'} = $dev[rand(@dev)];
$sheet->Cells($row,5)->{'Value'} = $bro[rand(@bro)];
$sheet->Cells($row,6)->{'Value'} = $app[rand(@app)];
++$row;
}
}
poj
PS: Many thanks to bmann for this post which solved the problem I got stuck on
|