Change charts title by PhpOffice\PhpSpreadsheet in template - php

I try to change chart title in .xlsx template
I open template, change cels ,write to output.
Q: How to change chart title....
$reader = IOFactory::createReader( 'Xlsx' );
$reader->setIncludeCharts( true );
$spreadsheet = $reader->load( storage_path( 'app/template.xlsx' ) );
$spreadsheet->getActiveSheet()->setCellValue( 'B3', 'Blabla' );
//create new from template
$writer = new Xlsx( $spreadsheet );
$writer->setPreCalculateFormulas( true );
$writer->setIncludeCharts( true );
##how to change title in all/first charts in template?

I finally found the method. There are a few things to understand.
chartIndex - In an excel file, an id assigned to the chart based on the total number of charts starting from the first left most chart on a sheetA incrementing to the last right most chart on SheetC. This index is the entire collection of all charts on all sheets starting with chart1 and ending with chartX. If you have ten charts chart1,chart2,...chart10 and delete chart5, you will then have a new index of chart1,chart2....chart9, where the orig chart6-10 are all redindexed as chart5-9. In phpspreadsheet, this index appears to be represented with $chart->getName() ;, There is no corresponding setName() that would allow you to change/alter the index.
chartName - In an excel file, if you highlight a chart, in the upper left corner of the cells, above the A column, is a "chart name" drop down. You can name your charts for organization purposes. In excel, this field can be edited. In phpspreadsheet, I have yet to have find what object can get/set this field.
chartTitle - the in chart name of a chart, IE: "Annual Revenue Projections". In phpspreadsheet, this field is represented with $chart->getTitle->get/setCaptionText
So in order to find the chart you are looking to modify, you either must already know the chart index (ie: getName()) OR the chart visual title (ie: getCaptionText() ).
Because of adding deleting moving charts, I found it easier, in the excel template, to add visual titles to your charts then search for those titles/captionText in your code. This way you don't have to have worry about tracking which chart is which index. Use the getCaptionText to then get the getName() index.
foreach ($spreadsheet->getSheetByName("SheetName")->getChartCollection() as $chart) {
// if you know TITLE of the chart
// TITLE is the visible title in the chart
// Easy to know if you set the titles yourself in the template chart
// A template chart TITLE cannot be a cell reference, will cause an error on file import
if ($chart->getTitle()->getCaptionText() == "Chart_12") {
$curIndex = $chart->getName() ; // = "chart3"
$curTitle = $chart->getTitle()->getCaptionText() ; // "Chart_12"
$chart->getTitle()->setCaption("Quarterly Revenue Chart") ;
break ;
}
// if you know the NAME (chart id) the chart
// NAME is like the hidden chart index
if ($chart->getName() == "chart12") {
$chart->getTitle()->setCaption("New Chart Title") ;
break ;
}
}

Related

PHPExcel Piechart legends with fix length

I have issue in setting the width of the legend lables.
I can show them but not able to show them as per expectation.
Currently it is looking like this
I want the Legend to be displayed like this
My code
//NOTE Layer for charts
$layout=new \PHPExcel_Chart_Layout();
$layout->setShowVal(true);
$layout->setShowPercent(true);
// Set series in the plot area
$pa=new \PHPExcel_Chart_PlotArea($layout, array($ds));
// Set legend
$legend=new \PHPExcel_Chart_Legend(\PHPExcel_Chart_Legend::POSITION_BOTTOM, NULL, false);
//Create Chart
$chart= new \PHPExcel_Chart('chart1',$title,$legend,$pa,true,0,NULL, NULL);
$chart->setTopLeftPosition('K'.$chart_index);
$chart->setBottomRightPosition('S'.($chart_index+20));
$ews2->addChart($chart);
I have got the solution for my problem.
I have just created array with expected label;
$pie_label = array($ea->getActiveSheet()->getCell("E".$i)->getValue(),$ea->getActiveSheet()->getCell("F".$i)->getValue(),$ea->getActiveSheet()->getCell("G".$i)->getValue(),$ea->getActiveSheet()->getCell("H".$i)->getValue());
and append it at end of the funtion of PHPExcel_Chart_DataSeriesValues,and converted my second parameter of function to null.
$spec_label = array(new \PHPExcel_Chart_DataSeriesValues('String', null, NULL, 1,$pie_label),);

How do I get the correct format x-axis for my phpspreadsheet chart?

I am using 33_Chart_create_scatter.php to make a two line xyScatter chart. Everything is going well, except, the x-axis is not formatting as I would like it to. There is no associated error involver. Only a poor x-axis. See the first image. For the correct (desired) x-axis, see the second image. Can someone help me achive the proper x-axis format?
I got the correct format x-axis by simply right clicking the chart area and selecting "Change Chart Type". Then I select (already selected) "X Y (Scatter)" and "ok". The x-axis is changed to that shown in my correct x-axis image. So, that brings about my second question, if I can not get a code correction to get the proper x-axis format, can we include macro's in our create charts? A simple three line auto_open macro included will yield the proper chart/x-axis when the new spreadsheet is opened.
I've used both horizontal and vertical selections for source values. I've also tried using specific values for the source. See J1:R1 in my image. I can not figure out how to add my images. So, incorrect x-axis runs from 1 to about 50 by 1's And it looks like there maybe two to three sets of numbers all crunched together. The correct scale is 0 to 40 by 5's evenly spaced. this is a minutes scale. The y scale looks perfect.
Here is the code involved.
$xAxisTickValues = [
new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$C$1:$C$18', null, 18),
new
DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$F$1:$F$18', null, 18)
];
The following code should control the x and y properties. I am able to control all the properties of the Y-axis. How ever it appears the x-axis min and max values are controlled by the x Axis Tick Values. If I don't use x Axis Tick Values, It then appears x-axis min and max values are controlled by the number of y data points?
What do I have to do so this code can be used to control x-axis min and max values?
$xaxis = new Axis();
$xaxis->setAxisOptionsProperties('low', 0, 'autoZero', null, 'in', 'out', 0, 40, 5, 0);
$title = new Title('Calorimetric Calibration');
$yAxisLabel = new Title(html_entity_decode('Temp (°C)',ENT_QUOTES,'UTF-8'));
$xAxisLabel = new Title('Time (Min)');
// Create the chart
$chart = new Chart(
'chart1', // name
$title, // title
$legend, // legend
$plotArea, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
$xAxisLabel, // xAxisLabel
$yAxisLabel, // yAxisLabel
$yaxis,
$xaxis,
null,
null
);

Laravel 5.5 Console TV Bar Chart High Charts multipleDatasets and label

I have a Laravel 5.5 app that used this ConsoleTV Chart Package I used a barchart to visualize my data in a monthly report basis. I have the following query below.
$dt = Carbon::now()->year;
$anRequest = AnalysisRequest::where(DB::raw("(DATE_FORMAT(created_at,'%Y'))"),date('Y'))->orderBy('service_id')
->get();
and in my chart
$barChart = Charts::database($anRequest, 'bar', 'highcharts')
->title("Monthly service request")
->elementLabel("Total requests")
->dimensions(1000, 500)
->responsive(false)
->groupByMonth(date('Y'), true);
This code is working perfectly fine and display all the data in by month but how can I add another dataSets or multipleDataSets instead of just having one sets of data to visualize.
For example I will have another query from the AnalysisRequest but with a specific resources.
Sample code below using multi
The query
$tags_jan = DB::table('tags')->whereYear('created_at', $dt)->whereMonth('created_at', '1')->count();
$tags_feb = DB::table('tags')->whereYear('created_at', $dt)->whereMonth('created_at', '2')->count();
$tags_mar = DB::table('tags')->whereYear('created_at', $dt)->whereMonth('created_at', '3')->count();
// and the list goes on which is bad
The charts using multi
$chart = Charts::multi('bar', 'highcharts')
// Setup the chart settings
->title("Total Reports for this year")
// A dimension of 0 means it will take 100% of the space
->dimensions(0, 400) // Width x Height
// This defines a preset of colors already done:)
// ->template("material")
// ->responsive(true)
// You could always set them manually
// ->colors(['#2196F3', '#F44336', '#FFC107'])
// Setup the diferent datasets (this is a multi chart)
->colors(['green', 'aqua', 'red', 'yellow'])
->dataset('Ads', [$ads_jan,$ads_feb,$ads_mar,$ads_apr,$ads_may,$ads_june,$ads_july,$ads_aug,$ads_sept,$ads_oct,$ads_nov,$ads_dec])
->dataset('Channels', [$channels_jan,$channels_feb,$channels_mar,$channels_apr,$channels_may,$channels_june,$channels_july,$channels_aug,$channels_sept,$channels_oct,$channels_nov,$channels_dec])
->dataset('Shows', [$shows_jan,$shows_feb,$shows_mar,$shows_apr,$shows_may,$shows_june,$shows_july,$shows_aug,$shows_sept,$shows_oct,$shows_nov,$shows_dec])
->dataset('Tags', [$tags_jan,$tags_feb,$tags_mar,$tags_apr,$tags_may,$tags_june,$tags_july,$tags_aug,$tags_sept,$tags_oct,$tags_nov,$tags_dec])
This code above also works fine but as you can see in the variable I am querying for each month for this year which is isn't quite good. How can I simplified this query or another way to solve this using multiple dataSets?
Appreciate if someone could help.
Thanks in advance.
The following code can be added after you have queried your database and you would like to post different graphs to the same view, I was using the code to plot a barchart and line chart on the same graph as specified below........ look at the dataset position 2 its line and bar
$chart = new unclaimed;
$chart->labels( $days );
$chart->dataset('Daily Visitors Bar', 'bar', $totalNumber )->color('white')->backgroundColor(['#009900','#8a8a5c','#f1c40f','#e67e22','#16a085','#2980b9']);
$chart->dataset('Daily Visitors Line', 'line', $totalNumber )->color('black') ->fill(false)->backgroundColor(['##8a8a5c','009900','#f1c40f','#e67e22','#16a085','#2980b9']);

how can I add labels for accumulated bars at the x-axis in jpgraph

How can I add labels for my accumulated bars in jpGraph?
I can add two accumulated bar plots which consist of several bar plots.
At the x-axis there are labels for the year of the data shown.
Is it possible to add a label above or below (in example image red and blue arrows) the accumulated graphs?
In the legend there would be the names of the data entries (like percentage of whatever is green, percentage of whatever 2 is blue ...)
Based on jpGraph Example 14.3 you could try to set the labels manually.
The PHP code of Example 14.3 is:
require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_bar.php');
// Some data
for($i=0; $i < 12; ++$i) {
$databary[$i] = rand(1,20);
}
$months=$gDateLocale->GetShortMonth();
// New graph with a drop shadow
$graph = new Graph(300,200);
$graph->SetShadow();
// Use a "text" X-scale
$graph->SetScale('textlin');
// Specify X-labels
$graph->xaxis->SetTickLabels($months);
$graph->xaxis->SetTextLabelInterval(2);
// Set title and subtitle
$graph->title->Set('Textscale with tickinterval=2');
// Use built in font
$graph->title->SetFont(FF_FONT1,FS_BOLD);
// Create the bar plot
$b1 = new BarPlot($databary);
$b1->SetLegend('Temperature');
// The order the plots are added determines who's ontop
$graph->Add($b1);
// Finally output the image
$graph->Stroke();
Example 14.3
On the above example if you check the $months variable you will notice that it is an array of short month names ["Jan","Feb","Mar",...,"Dec"] returned by Function GetShortMonth() used in jpGraph DateLocale Class. What you could do is manually create an array of the desired labels in your graph, or populate an array of the desired labels per each accumulated bar stack (depends on your code). The PHP code of Example 14.3 indicates that functions SetTickLabels() and SetTextLabelInterval() are the ones used to set and properly position the x-Axis labels.
// Specify X-labels
$graph->xaxis->SetTickLabels($months);
$graph->xaxis->SetTextLabelInterval(2);

Sample Scatter Excel Chart using OpenTBS

Can anybody give me an example of how to create an Excel Scatter chart using OpenTBS/TinyButStrong? And are there any commercial/non-commercial PHP excel writers that support excel charts?
Will really appreciate your help.
Thank you for your time!
Create a basic XY chart using the wizard in Ms Word.
Save the chart without changing it. Let the values and the design.
Select the chart, and in the contextual menu, chose "Format of the zone" or something like this. In the "Alt Text" tab, in zone "Title", enter "a nice chart".
Save the template.
At the PHP side:
$template = 'demo_ms_word.docx'; $TBS->LoadTemplate($template);
$ChartNameOrNum = 'a nice chart'; // Title of the shape that embeds the chart
$SeriesNameOrNum = 1;
$NewValues = array( array( 1.5, 2.0, 3.2, 33), array(1.77, 2.88, 2.88, 2.99) );
$NewLegend = "OpenTBS is so strong";
$TBS->PlugIn(OPENTBS_CHART, $ChartNameOrNum, $SeriesNameOrNum, $NewValues, $NewLegend);
$TBS->Show(OPENTBS_FILE+TBS_EXIT, 'result.docx');
After it works, change the chart properties and the data.

Categories