1

I have so far successfully exported data from Mysql into Excel via PHPExcel, made my tables, formatted, and everything is hunky dory.

However, so far any attempt at making graphs from said tables failed miserably. Not only, after days on end of Google Search, I've not found a simple example/tutorial on how to populate the graph values from MySQL.

It all boils down to this:

Taken from https://github.com/affinitybridge/phpexcel/blob/master/Tests/33chartcreate-pie.php

/** PHPExcel */
include 'PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
$objWorksheet->fromArray(
    array(
        array('',   2010,   2011,   2012),
        array('Q1',   12,   15,     21),
        array('Q2',   56,   73,     86),
        array('Q3',   52,   61,     69),
        array('Q4',   30,   32,     0),
    )
);

How the hell do I populate $objWorksheet->fromArray from either a) Mysql or b) excel.

If it's SQL, I would need to run this query for all the tables in my database.

$sql = "SELECT Functional_Area, Passed__Status , Blocked__Status , Failed__Status FROM $tbl_name WHERE 1;

Context: I have several Functional Areas, each of them has different values in Passed/Failed/Blocked. I need 1 Graph for each Functional Areas. On average I have 14 functional areas per each Table.

I would then construct a Pie chart (or Bar chart, I'm not fussy) for each Functional Area.

Option 2) Excel

Since I already have said data in an excel, I would need to populate the data from:

enter image description here

Again, 1 graph for each ROW (ROW 5 (FA = EPG) will be 1 graph, ROW 6 (FA = VOD) will be another graph, etc...).

This will have to be repeated for EACH worksheet...

My attempt so far is below, this produces for each worksheet (and this is good) a graph, which however is empty (not good).

foreach (glob("*.xls") as $f) 
{
    $inputFileName = $f;    
    echo "Found $inputFileName <br/>";  
}


//  Read your Excel workbook

        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
        $i = 0;
        foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) 
            {
                $arrayData[$worksheet->getTitle()] = $worksheet->toArray();
                echo "Title: ".$worksheet->getTitle()."<br/>"; 
                $wsTitle = $worksheet->getTitle();

                $objWorksheet = $objPHPExcel->setActiveSheetIndexByName($wsTitle);

                $highestRow         = $worksheet->getHighestRow(); // e.g. 10
                $endofData = $highestRow -1;
                $highestColumn      = $worksheet->getHighestColumn(); // e.g 'F'
                $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
                $colNumberStart = PHPExcel_Cell::columnIndexFromString("D");
                $BeforeTOT = $colNumberStart - 2;            
                $TOT = $colNumberStart - 1;             
                echo "Highest Row is ==> $highestRow <br/>End of Data - header is $endofData <br/> Highest Col is ==>  $highestColumn <br/> Start col is ==> $colNumberStart and Highest Col end is ==> $highestColumnIndex <br/>";




                //  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' . $i} = array(
                    new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$4', null, 1),   //  2010
                    new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$G$4', null, 1),   //  2011
                    new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$H$4', null, 1),   //  2012
                    new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$I$4', null, 1),   //  2012
                );

                displayArray(${'dataseriesLabels' . $i});
                //  Set the X-Axis Labels
                //      Datatype
                //      Cell reference for data
                //      Format Code
                //      Number of datapoints in series
                //      Data values
                //      Data Marker
                ${'xAxisTickValues' . $i} = array(
                    new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$4:$H$4', null, 19), //  Q1 to Q4
                );
                displayArray(${'xAxisTickValues' . $i});
                //  Set the Data values for each data series we want to plot
                //      Datatype
                //      Cell reference for data
                //      Format Code
                //      Number of datapoints in series
                //      Data values
                //      Data Marker
                ${'dataSeriesValues' . $i} = array(
                    new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$G$5:$I$5', null, 4),  
                );
                displayArray(${'dataSeriesValues' . $i});
                //  Build the dataseries
                ${'series' . $i} = new PHPExcel_Chart_DataSeries(
                    PHPExcel_Chart_DataSeries::TYPE_PIECHART,               // plotType
                    PHPExcel_Chart_DataSeries::GROUPING_PERCENT_STACKED,    // plotGrouping
                    range(0, count(${'dataseriesLabels' . $i})-1),                  // plotOrder
                    ${'dataseriesLabels' . $i},                                     // plotLabel
                    ${'xAxisTickValues' . $i},                                      // plotCategory
                    ${'dataSeriesValues' . $i}                                      // plotValues
                );

                displayArray(${'series' . $i});
                //  Set the series in the plot area
                ${'plotarea' . $i} = new PHPExcel_Chart_PlotArea(null, array(${'series' . $i}));
                //  Set the chart legend
                ${'legend' . $i} = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_TOPRIGHT, null, false);
                ${'title' . $i} = new PHPExcel_Chart_Title('Test %age-Stacked Area Chart');
                ${'yAxisLabel' . $i} = new PHPExcel_Chart_Title('Value ($k)');
                //  Create the chart
                ${'chart' . $i} = new PHPExcel_Chart(
                    'chart1',       // name
                    ${'title' . $i},        // title
                    ${'legend' . $i},       // legend
                    ${'plotarea' . $i},     // plotArea
                    true,           // plotVisibleOnly
                    0,              // displayBlanksAs
                    null,           // xAxisLabel
                    ${'yAxisLabel' . $i}    // yAxisLabel
                );
                //  Set the position where the chart should appear in the worksheet
                ${'chart' . $i}->setTopLeftPosition('A7');
                ${'chart' . $i}->setBottomRightPosition('H20');
                //  Add the chart to the worksheet
                $objWorksheet->addChart(${'chart' . $i});
                //  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

                // Save Excel 2007 file
                echo date('H:i:s') , " Write to Excel2007 format" , EOL;
                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
                $objWriter->setIncludeCharts(TRUE);
                $objWriter->save(str_replace('.php', '.xlsx', __FILE__));
                echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
                // Echo memory peak usage
                echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
                // Echo done
                echo date('H:i:s') , " Done writing file" , EOL;
                echo 'File has been created in ' , getcwd() , EOL;
                $i++;
}
user3375601
  • 119
  • 2
  • 9
  • If you're already "successfully exported data from Mysql into Excel via PHPExcel", then you don't need to re-populate it using `fromArray()`.... `fromArray()` is simply a method that will set a series of cell values in a single call from a PHP array of data.... it is not specific to charts in any way – Mark Baker Sep 08 '15 at 07:30
  • Indeed, already can export and dump values from Mysql to Excel via fromArray to begin with. for example: ` $sql = "SELECT * FROM $value"; $arr = db_select($sql); $objPHPExcel->getActiveSheet()->fromArray($arr, NULL, 'C5');` dump the content of query $sql into an excel sheet (code shortened for clarity)... However, all my graphs have blank values and the only reason I could think of is that I'm not populating the fromArray values? – user3375601 Sep 08 '15 at 07:52
  • Well if you save your worksheet without the charts, then you can check the values in the saved file to be certain that they're there – Mark Baker Sep 08 '15 at 08:02
  • But as a first point of note.... you're setting worksheet names using a variable `$wsTitle`, but the cell ranges that you're referencing in your calls to set the chart data series are all referencing `Worksheet` as the worksheet name.... `Worksheet` isn't a "magic word" – Mark Baker Sep 08 '15 at 08:04
  • When you see something like `Worksheet!$I$4` or `'Worksheet!$G$5:$I:5` in an Excel worksheet, then it's a cell or range reference: the part before the `!` is a worksheet name, the part after the `!` is the cell or cell range in that worksheet..... this is standard Excel – Mark Baker Sep 08 '15 at 08:06
  • Fellas, I had some more investigations and came to some answers. a. if data is on excel, you don't need to query it from Mysql b. Here is a snippet that works, 100% of time in making a stacked bar chart from a worksheet already populated previously: `code` – user3375601 Sep 22 '15 at 12:46
  • See below for latest hurdle, sorry didn't fit in comments all the code. Help is appreciated as always. – user3375601 Sep 25 '15 at 11:22

1 Answers1

0

Fellas, I had some more investigations and came to some answers.

a. if data is on excel, you don't need to query it from Mysql b. Here is a snippet that works, 100% of time in making a stacked bar chart from a worksheet already populated previously:

                //  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
                $dataseriesLabels1 = array(
                    new PHPExcel_Chart_DataSeriesValues('String', 'report!$E$4', NULL, 4),    //  Jan to Dec
                    new PHPExcel_Chart_DataSeriesValues('String', 'report!$F$4', NULL, 4),    //  Jan to Dec
                    new PHPExcel_Chart_DataSeriesValues('String', 'report!$G$4', NULL, 4)    //  Jan to Dec
                );

                //  Set the X-Axis Labels
                //      Datatype
                //      Cell reference for data
                //      Format Code
                //      Number of datapoints in series
                //      Data values
                //      Data Marker

                $xAxisTickValues = array(
                    new PHPExcel_Chart_DataSeriesValues('String', 'report!$C$4:$C$20', NULL, 4)    //  Jan to Dec    
                );

                //  Set the Data values for each data series we want to plot
                //      Datatype
                //      Cell reference for data
                //      Format Code
                //      Number of datapoints in series
                //      Data values
                //      Data Marker
                $dataSeriesValues1 = array(
                    new PHPExcel_Chart_DataSeriesValues('Number', 'report!$E$5:$E$20', NULL, 16),
                    new PHPExcel_Chart_DataSeriesValues('Number', 'report!$F$5:$F$20', NULL, 16),
                    new PHPExcel_Chart_DataSeriesValues('Number', 'report!$G$5:$G$20', NULL, 16)
                );

                //  Build the dataseries
                $series1 = new PHPExcel_Chart_DataSeries(
                    PHPExcel_Chart_DataSeries::TYPE_BARCHART,        // plotType
                    PHPExcel_Chart_DataSeries::GROUPING_STACKED,    // plotGrouping
                    range(0, count($dataSeriesValues1)-1),          // plotOrder
                    $dataseriesLabels1,                             // plotLabel
                    $xAxisTickValues,                               // plotCategory
                    $dataSeriesValues1                              // plotValues
                );
                //  Set additional dataseries parameters
                //      Make it a vertical column rather than a horizontal bar graph
                $series1->setPlotDirection(PHPExcel_Chart_DataSeries::DIRECTION_COL);

                //  Set the series in the plot area
                $plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series1));
                //  Set the chart legend
                $legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);

                $title = new PHPExcel_Chart_Title('Average Weather Chart for Crete');


                //  Create the chart
                $chart = new PHPExcel_Chart(
                    'chart1',       // name
                    $title,         // title
                    $legend,        // legend
                    $plotarea,      // plotArea
                    true,           // plotVisibleOnly
                    0,              // displayBlanksAs
                    NULL,           // xAxisLabel
                    NULL            // yAxisLabel
                );

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

                //  Add the chart to the worksheet
                $objWorksheet->addChart($chart);




                // Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
                $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
                $objWriter->setIncludeCharts(true);

d. So, to automate graph creation, the process will be: d1. Open w/e worksheet you need to get data from d2. read or hardcode the values for the labels, x and y axis d3. create the Chart element d4. Post said element w/e is desired.

Hope this helps some other poor coder out there having headaches with PHPExcel+Graphs

==========================================================================

Update 25/9

I am trying to build the arrays dynamically, but a bit failing.

  Fellas, question.

I am now trying to populate this dynamically, in other words, build:

   $dataseriesLabels1 = "array(";

   foreach ($Labels as $k => $s) 
   {
     echo "Parsing $s <br/>";
     $dataseriesLabels1 .= "new PHPExcel_Chart_DataSeriesValues('String', ".$s.", NULL, 4),";
     // echo "We have $dataseriesLabels1 in this loop <br/>";
   }
   $dataseriesLabels1 = rtrim($dataseriesLabels1, "," );
   $dataseriesLabels1 .= ");";

    echo "BUilt : $dataseriesLabels1 <br/>";

This is all good, since it creates for me:

   array(new PHPExcel_Chart_DataSeriesValues('String', 'Sprint!$D$4:$D$16', NULL, 4),new PHPExcel_Chart_DataSeriesValues('String', 'Sprint!$E$4:$E$16', NULL, 4),new PHPExcel_Chart_DataSeriesValues('String', 'Sprint!$F$4:$F$16', NULL, 4),new PHPExcel_Chart_DataSeriesValues('String', 'Sprint!$G$4:$G$16', NULL, 4),new PHPExcel_Chart_DataSeriesValues('String', 'Sprint!$H$4:$H$16', NULL, 4));

Unfortunately, this gets interpreted as a string, not an array, therefore the chart generation fails :/

Ideas?

user3375601
  • 119
  • 2
  • 9