Skip to content

More Bubble Chart Fixes #2856

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -4547,7 +4547,7 @@ parameters:

-
message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#"
count: 43
count: 42
path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php

-
Expand Down
124 changes: 124 additions & 0 deletions samples/Chart/33_Chart_create_bubble.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
<?php

use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\Chart\DataSeries;
use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues;
use PhpOffice\PhpSpreadsheet\Chart\Legend as ChartLegend;
use PhpOffice\PhpSpreadsheet\Chart\PlotArea;
use PhpOffice\PhpSpreadsheet\Chart\Title;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

require __DIR__ . '/../Header.php';

$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->fromArray(
[
['Number of Products', 'Sales in USD', 'Market share'],
[14, 12200, 15],
[20, 60000, 33],
[18, 24400, 10],
[22, 32000, 42],
[],
[12, 8200, 18],
[15, 50000, 30],
[19, 22400, 15],
[25, 25000, 50],
]
);

// Set the Labels for each data series we want to plot
// Datatype
// Cell reference for data
// Format Code
// Number of datapoints in series
// Data values
// Data Marker

$dataSeriesLabels = [
new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, null, null, 1, ['2013']), // 2013
new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, null, null, 1, ['2014']), // 2014
];

// Set the X-Axis values
// Datatype
// Cell reference for data
// Format Code
// Number of datapoints in series
// Data values
// Data Marker
$dataSeriesCategories = [
new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$A$2:$A$5', null, 4),
new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$A$7:$A$10', null, 4),
];

// Set the Y-Axis values
// Datatype
// Cell reference for data
// Format Code
// Number of datapoints in series
// Data values
// Data Marker
$dataSeriesValues = [
new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$5', null, 4),
new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$7:$B$10', null, 4),
];

// Set the Z-Axis values (bubble size)
// Datatype
// Cell reference for data
// Format Code
// Number of datapoints in series
// Data values
// Data Marker
$dataSeriesBubbles = [
new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$5', null, 4),
new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$7:$C$10', null, 4),
];

// Build the dataseries
$series = new DataSeries(
DataSeries::TYPE_BUBBLECHART, // plotType
null, // plotGrouping
range(0, count($dataSeriesValues) - 1), // plotOrder
$dataSeriesLabels, // plotLabel
$dataSeriesCategories, // plotCategory
$dataSeriesValues // plotValues
);
$series->setPlotBubbleSizes($dataSeriesBubbles);

// Set the series in the plot area
$plotArea = new PlotArea(null, [$series]);
// Set the chart legend
$legend = new ChartLegend(ChartLegend::POSITION_RIGHT, null, false);

// Create the chart
$chart = new Chart(
'chart1', // name
null, // title
$legend, // legend
$plotArea, // plotArea
true, // plotVisibleOnly
DataSeries::EMPTY_AS_GAP, // displayBlanksAs
null, // xAxisLabel
null // yAxisLabel
);

// Set the position where the chart should appear in the worksheet
$chart->setTopLeftPosition('E1');
$chart->setBottomRightPosition('M15');

// Add the chart to the worksheet
$worksheet->addChart($chart);
$worksheet->getColumnDimension('A')->setAutoSize(true);
$worksheet->getColumnDimension('B')->setAutoSize(true);
$worksheet->getColumnDimension('C')->setAutoSize(true);

// Save Excel 2007 file
$filename = $helper->getFilename(__FILE__);
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->setIncludeCharts(true);
$callStartTime = microtime(true);
$writer->save($filename);
$helper->logWrite($writer, $filename, $callStartTime);
Binary file added samples/templates/32readwriteBubbleChart2.xlsx
Binary file not shown.
15 changes: 15 additions & 0 deletions src/PhpSpreadsheet/Chart/Chart.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,9 @@ class Chart
/** @var ?int */
private $perspective;

/** @var bool */
private $oneCellAnchor = false;

/**
* Create a new Chart.
*
Expand Down Expand Up @@ -743,4 +746,16 @@ public function setPerspective(?int $perspective): self

return $this;
}

public function getOneCellAnchor(): bool
{
return $this->oneCellAnchor;
}

public function setOneCellAnchor(bool $oneCellAnchor): self
{
$this->oneCellAnchor = $oneCellAnchor;

return $this;
}
}
29 changes: 29 additions & 0 deletions src/PhpSpreadsheet/Chart/DataSeries.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,13 @@ class DataSeries
*/
private $plotValues = [];

/**
* Plot Bubble Sizes.
*
* @var DataSeriesValues[]
*/
private $plotBubbleSizes = [];

/**
* Create a new DataSeries.
*
Expand Down Expand Up @@ -339,6 +346,28 @@ public function getPlotValuesByIndex($index)
return false;
}

/**
* Get Plot Bubble Sizes.
*
* @return DataSeriesValues[]
*/
public function getPlotBubbleSizes(): array
{
return $this->plotBubbleSizes;
}

/**
* Set Plot Bubble Sizes.
*
* @param DataSeriesValues[] $plotBubbleSizes
*/
public function setPlotBubbleSizes(array $plotBubbleSizes): self
{
$this->plotBubbleSizes = $plotBubbleSizes;

return $this;
}

/**
* Get Number of Plot Series.
*
Expand Down
2 changes: 1 addition & 1 deletion src/PhpSpreadsheet/Chart/DataSeriesValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ public function setLineWidth($width)
*/
public function isMultiLevelSeries()
{
if (count($this->dataValues) > 0) {
if (!empty($this->dataValues)) {
return is_array(array_values($this->dataValues)[0]);
}

Expand Down
39 changes: 35 additions & 4 deletions src/PhpSpreadsheet/Reader/Xlsx.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@ private function loadZipNonamespace(string $filename, string $ns): SimpleXMLElem
Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_DRAWING,
];

private const REL_TO_CHART = [
Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_CHART,
];

/**
* Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
*
Expand Down Expand Up @@ -408,17 +412,21 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet

// Read the theme first, because we need the colour scheme when reading the styles
[$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName();
$drawingNS = self::REL_TO_DRAWING[$xmlNamespaceBase] ?? Namespaces::DRAWINGML;
$chartNS = self::REL_TO_CHART[$xmlNamespaceBase] ?? Namespaces::CHART;
$wbRels = $this->loadZip("xl/_rels/${workbookBasename}.rels", Namespaces::RELATIONSHIPS);
$theme = null;
$this->styleReader = new Styles();
foreach ($wbRels->Relationship as $relx) {
$rel = self::getAttributes($relx);
$relTarget = (string) $rel['Target'];
if (substr($relTarget, 0, 4) === '/xl/') {
$relTarget = substr($relTarget, 4);
}
switch ($rel['Type']) {
case "$xmlNamespaceBase/theme":
$themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2'];
$themeOrderAdditional = count($themeOrderArray);
$drawingNS = self::REL_TO_DRAWING[$xmlNamespaceBase] ?? Namespaces::DRAWINGML;

$xmlTheme = $this->loadZip("xl/{$relTarget}", $drawingNS);
$xmlThemeName = self::getAttributes($xmlTheme);
Expand Down Expand Up @@ -1204,12 +1212,20 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet
. '/_rels/'
. basename($fileWorksheet)
. '.rels';
if (substr($drawingFilename, 0, 7) === 'xl//xl/') {
$drawingFilename = substr($drawingFilename, 4);
}
if ($zip->locateName($drawingFilename)) {
$relsWorksheet = $this->loadZipNoNamespace($drawingFilename, Namespaces::RELATIONSHIPS);
$drawings = [];
foreach ($relsWorksheet->Relationship as $ele) {
if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") {
$drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
$eleTarget = (string) $ele['Target'];
if (substr($eleTarget, 0, 4) === '/xl/') {
$drawings[(string) $ele['Id']] = substr($eleTarget, 1);
} else {
$drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
}
}
}

Expand All @@ -1234,7 +1250,13 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet
$images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']);
} elseif ($eleType === "$xmlNamespaceBase/chart") {
if ($this->includeCharts) {
$charts[self::dirAdd($fileDrawing, $ele['Target'])] = [
$eleTarget = (string) $ele['Target'];
if (substr($eleTarget, 0, 4) === '/xl/') {
$index = substr($eleTarget, 1);
} else {
$index = self::dirAdd($fileDrawing, $eleTarget);
}
$charts[$index] = [
'id' => (string) $ele['Id'],
'sheet' => $docSheet->getTitle(),
];
Expand Down Expand Up @@ -1326,6 +1348,7 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet
'width' => $width,
'height' => $height,
'worksheetTitle' => $docSheet->getTitle(),
'oneCellAnchor' => true,
];
}
}
Expand Down Expand Up @@ -1645,7 +1668,7 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet
if ($this->includeCharts) {
$chartEntryRef = ltrim((string) $contentType['PartName'], '/');
$chartElements = $this->loadZip($chartEntryRef);
$chartReader = new Chart();
$chartReader = new Chart($chartNS, $drawingNS);
$objChart = $chartReader->readChart($chartElements, basename($chartEntryRef, '.xml'));
if (isset($charts[$chartEntryRef])) {
$chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
Expand All @@ -1662,6 +1685,9 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet
// oneCellAnchor or absoluteAnchor (e.g. Chart sheet)
$objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
$objChart->setBottomRightPosition('', $chartDetails[$chartPositionRef]['width'], $chartDetails[$chartPositionRef]['height']);
if (array_key_exists('oneCellAnchor', $chartDetails[$chartPositionRef])) {
$objChart->setOneCellAnchor($chartDetails[$chartPositionRef]['oneCellAnchor']);
}
}
}
}
Expand Down Expand Up @@ -1823,6 +1849,11 @@ private static function getArrayItem($array, $key = 0)

private static function dirAdd($base, $add): string
{
$add = "$add";
if (substr($add, 0, 4) === '/xl/') {
$add = substr($add, 4);
}

return (string) preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
}

Expand Down
22 changes: 19 additions & 3 deletions src/PhpSpreadsheet/Reader/Xlsx/Chart.php
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ private function chartDataSeries(SimpleXMLElement $chartDetail, string $plotType
{
$multiSeriesType = null;
$smoothLine = false;
$seriesLabel = $seriesCategory = $seriesValues = $plotOrder = [];
$seriesLabel = $seriesCategory = $seriesValues = $plotOrder = $seriesBubbles = [];

$seriesDetailSet = $chartDetail->children($this->cNamespace);
foreach ($seriesDetailSet as $seriesDetailKey => $seriesDetails) {
Expand Down Expand Up @@ -382,6 +382,10 @@ private function chartDataSeries(SimpleXMLElement $chartDetail, string $plotType
case 'yVal':
$seriesValues[$seriesIndex] = $this->chartDataSeriesValueSet($seriesDetail, "$marker", "$srgbClr", "$pointSize");

break;
case 'bubbleSize':
$seriesBubbles[$seriesIndex] = $this->chartDataSeriesValueSet($seriesDetail, "$marker", "$srgbClr", "$pointSize");

break;
case 'bubble3D':
$bubble3D = self::getAttribute($seriesDetail, 'val', 'boolean');
Expand Down Expand Up @@ -435,9 +439,11 @@ private function chartDataSeries(SimpleXMLElement $chartDetail, string $plotType
}
}
}

/** @phpstan-ignore-next-line */
return new DataSeries($plotType, $multiSeriesType, $plotOrder, $seriesLabel, $seriesCategory, $seriesValues, $smoothLine);
$series = new DataSeries($plotType, $multiSeriesType, $plotOrder, $seriesLabel, $seriesCategory, $seriesValues, $smoothLine);
$series->setPlotBubbleSizes($seriesBubbles);

return $series;
}

/**
Expand Down Expand Up @@ -494,6 +500,16 @@ private function chartDataSeriesValueSet(SimpleXMLElement $seriesDetail, ?string
return $seriesValues;
}

if (isset($seriesDetail->v)) {
return new DataSeriesValues(
DataSeriesValues::DATASERIES_TYPE_STRING,
null,
null,
1,
[(string) $seriesDetail->v]
);
}

return null;
}

Expand Down
2 changes: 2 additions & 0 deletions src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,5 +76,7 @@ class Namespaces

const PURL_DRAWING = 'http://purl.oclc.org/ooxml/drawingml/main';

const PURL_CHART = 'http://purl.oclc.org/ooxml/drawingml/chart';

const PURL_WORKSHEET = 'http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet';
}
Loading