Fatal error for rendering PHPExcel Stock chart with jpgraph - phpexcel
I've been working with PHPExcel since a while, and so far it has done great rendering all the charts I needed. However, a problem came when I was trying to create and render (using jpgraph) a stock chart.
There wasn't any example set in the download package, but I noticed that PHPExcel do support stock graph. So I looked into the chart.xml file that Excel2007 creates and used that as a hint to make an example of my own. Below are the codes:
<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
date_default_timezone_set('Europe/London');
/**
* PHPExcel
*
* Copyright (C) 2006 - 2013 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* #category PHPExcel
* #package PHPExcel
* #copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* #license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* #version ##VERSION##, ##DATE##
*/
/** PHPExcel */
require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
$objWorksheet->fromArray(
array(
array('Counts', 'Max', 'Max Threshold', 'Min Threshold', 'Min'),
array('Count 10', 10, 50, 0, 5),
array('Count 30', 20, 50, 0, 10),
array('Count 10', 30, 50, 0, 15),
array('Count 10', 10, 50, 0, 0),
), null, 'A1', true
);
$objWorksheet->getStyle('B2:E5')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00);
// 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 = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1), //Max / High
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), //Max Threshold / Opening
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), //Min Threshold / Closing
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$E$1', NULL, 1), //Min / Low
);
// 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', 'Worksheet!$A$2:$A$5', NULL, 4), // Counts
);
// 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 = array(
new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$B$2:$B$5', NULL, 4),
new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$C$2:$C$5', NULL, 4),
new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$D$2:$D$5', NULL, 4),
new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$E$2:$E$5', NULL, 4),
);
// Build the dataseries
$series = new PHPExcel_Chart_DataSeries(
PHPExcel_Chart_DataSeries::TYPE_STOCKCHART, // plotType
null, // plotGrouping - if we set this to not null, then xlsx throws error
range(0, count($dataSeriesValues)-1), // plotOrder
$dataseriesLabels, // plotLabel
$xAxisTickValues, // plotCategory
$dataSeriesValues // plotValues
);
// Set the series in the plot area
$plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
$title = new PHPExcel_Chart_Title('Test Stock Chart');
// Create the chart
$chart = new PHPExcel_Chart(
'stock-chart', // 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('A7');
$chart->setBottomRightPosition('H20');
// Add the chart to the worksheet
$objWorksheet->addChart($chart);
$rendererName = PHPExcel_Settings::CHART_RENDERER_JPGRAPH;
$rendererLibrary = 'jpgraph';
$rendererLibraryPath = '../' . $rendererLibrary;
if (!PHPExcel_Settings::setChartRenderer(
$rendererName,
$rendererLibraryPath
)) {
die(
'NOTICE: Please set the $rendererName and $rendererLibraryPath values' .
EOL .
'at the top of this script as appropriate for your directory structure'
);
}
$chart->render('chart-stock.jpg');
// 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;
The code above, generates the xlsx file fine.
But the problem arrives, when I try to render the chart using jpgraph and save it. It throws a PHP Fatal error:
Fatal error: Call to a member function getDataValues() on a non-object in I:\wamp\www\phpexcel\Classes\PHPExcel\Chart\Renderer\jpgraph.php on line 525
I looked into the code and it seems, getPlotCategoryByIndex function for some reasons will not return the object. The most obvious thing I can think of is, I am not passing the plot correctly? But then again, I can not think of why and how I'd miss something in the $dataSeriesValues. Can anyone please guide me how to solve this?
Also, since I am new, I am not able to put images. So here is a link to download the screenshot, php file and the generated xlsx file.
https://dl.dropboxusercontent.com/u/129745839/PHPExcel%20Stockexchange/33chartcreate-stock.zip
Found the solution:
Okay, after a lot of trying, I finally solved it.
As it happens, the stock chart wasn't fully implemented. So I had to write the codes to complete it. Here's how to do this:
for /Classes/PHPExcel/Chart/Renderer/jpgraph.php we have to replace following two functions
private function _renderPlotStock($groupID) {
$seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
$plotOrder = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder();
$seriesPlots = array();
//var_dump($seriesCount);
$dataValues = array();
// Loop through each data series in turn
for($i = 0; $i < $seriesCount; ++$i) {
$dataValuesX = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues();
foreach($dataValuesX as $j => $dataValueX) {
$dataValues[$plotOrder[$i]][$j] = $dataValueX;
}
}
if(empty($dataValues)) {
return;
}
$dataValuesPlot = array();
for($j = 0; $j < count($dataValues[0]); $j++) {
for($i = 0; $i < $seriesCount; $i++) {
$dataValuesPlot[] = $dataValues[$i][$j];
}
}
$xAxisLabel = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues();
var_dump($xAxisLabel);
$seriesPlot = new StockPlot($dataValuesPlot, $xAxisLabel);
$seriesPlot->SetWidth(20);
$this->_graph->Add($seriesPlot);
} // function _renderPlotStock()
and
private function _renderStockChart($groupCount) {
require_once('jpgraph_stock.php');
//$this->_renderplotara
$this->_renderCartesianPlotArea('intint');
var_dump($groupCount);
for($groupID = 0; $groupID < $groupCount; ++$groupID) {
$this->_renderPlotStock($groupID);
}
} // function _renderStockChart()
also, the new example would be something like this
<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
date_default_timezone_set('Europe/London');
/**
* PHPExcel
*
* Copyright (C) 2006 - 2013 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* #category PHPExcel
* #package PHPExcel
* #copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* #license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* #version ##VERSION##, ##DATE##
*/
/** PHPExcel */
require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
$objWorksheet->fromArray(
array(
array('Counts', 'Max', 'Min', 'Min Threshold', 'Max Threshold' ),
array(10, 10, 5, 0, 50 ),
array(30, 20, 10, 0, 50 ),
array(20, 30, 15, 0, 50 ),
array(40, 10, 0, 0, 50 ),
array(100, 40, 5, 0, 50 ),
), null, 'A1', true
);
$objWorksheet->getStyle('B2:E6')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00);
// 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 = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1), //Max / Open
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), //Min / Close
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), //Min Threshold / Min
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$E$1', NULL, 1), //Max Threshold / Max
);
// 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', 'Worksheet!$A$2:$A$6', NULL, 5), // Counts
);
// 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 = array(
new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$B$2:$B$6', NULL, 5),
new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$C$2:$C$6', NULL, 5),
new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$D$2:$D$6', NULL, 5),
new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$E$2:$E$6', NULL, 5),
);
// Build the dataseries
$series = new PHPExcel_Chart_DataSeries(
PHPExcel_Chart_DataSeries::TYPE_STOCKCHART, // plotType
null, // plotGrouping - if we set this to not null, then xlsx throws error
range(0, count($dataSeriesValues)-1), // plotOrder
$dataseriesLabels, // plotLabel
$xAxisTickValues, // plotCategory
$dataSeriesValues // plotValues
);
// Set the series in the plot area
$plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
$title = new PHPExcel_Chart_Title('Test Stock Chart');
$xAxisLabel = new PHPExcel_Chart_Title('Counts');
$yAxisLabel = new PHPExcel_Chart_Title('Values');
// Create the chart
$chart = new PHPExcel_Chart(
'stock-chart', // name
$title, // title
$legend, // legend
$plotarea, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
$xAxisLabel, // xAxisLabel
$yAxisLabel // yAxisLabel
);
// Set the position where the chart should appear in the worksheet
$chart->setTopLeftPosition('A7');
$chart->setBottomRightPosition('H20');
// Add the chart to the worksheet
$objWorksheet->addChart($chart);
$rendererName = PHPExcel_Settings::CHART_RENDERER_JPGRAPH;
$rendererLibrary = 'jpgraph';
$rendererLibraryPath = '../' . $rendererLibrary;
if (!PHPExcel_Settings::setChartRenderer(
$rendererName,
$rendererLibraryPath
)) {
die(
'NOTICE: Please set the $rendererName and $rendererLibraryPath values' .
EOL .
'at the top of this script as appropriate for your directory structure'
);
}
if(file_exists('chart-stock.jpg')) {
unlink('chart-stock.jpg');
}
$chart->render('chart-stock.jpg');
// Save Excel 2007 file
echo date('H:i:s') , " Write to Excel2007 format" , EOL;
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->setIncludeCharts(TRUE);
$filename = str_replace('.php', '.xlsx', __FILE__);
if(file_exists($filename)) {
unlink($filename);
}
$objWriter->save($filename);
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;
Hope someone finds it useful.
Related
PHPExel LineChart: How can I display empty cell as a gap and not as 0 value
I would like to generate a LineChart with PHPExcel, where empty cells are not displayed as 0 values but displayed as a gap. In my code I tried in the constructor of PHPExcelChart a lot of different values for the argument "displayBlanksAs", such like ' ' or DISPLAY_BLANKS_AS_GAP or 'X' or NULL, etc. But nothing worked. The empty cell is always displayed as 0 not as a gap. Is there anyone, who has an idea?Many thanks in advance! Here my PHP-Code: <?php ... $dataSeriesValues = array( new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$D$58:$Q$58', NULL, 14),); $series = new PHPExcel_Chart_DataSeries( PHPExcel_Chart_DataSeries::TYPE_LINECHART, // plotType PHPExcel_Chart_DataSeries::GROUPING_STACKED, // plotGrouping range(0, count($dataSeriesValues)-1), // plotOrder NULL, // plotLabel NULL, // plotCategory $dataSeriesValues // plotValues); // Set the series in the plot area $plotArea = new PHPExcel_Chart_PlotArea(NULL, array($series)); // Create the Chart $chart = new PHPExcel_Chart( 'chart1', // name NULL, // title NULL, // legend $plotArea, // plotArea true, // plotVisibleOnly DISPLAY_BLANKS_AS_GAP, // displayBlanksAs => here I tried ' ',NULL,'X', etc., empty cells are always displayed as 0, not as a gap NULL, // xAxisLabel NULL // yAxisLabel ); // Set the position where the chart should appear in the worksheet $chart->setTopLeftPosition('R58'); $chart->setBottomRightPosition('X58'); $objPHPExcel->getActiveSheet()->addChart($chart); ?>
I found the answer myself: I had to change in the constructor of PHPExcel_Chart_DataSeries the plotGrouping - parameter from GROUPING_STACKED to GROUPING_STANDARD: $series = new PHPExcel_Chart_DataSeries( PHPExcel_Chart_DataSeries::TYPE_LINECHART, // plotType PHPExcel_Chart_DataSeries::GROUPING_STANDARD, // plotGrouping range(0, count($dataSeriesValues)-1), // plotOrder NULL, // plotLabel NULL, // plotCategory $dataSeriesValues // plotValues); Then the empty cells are displayed as gaps.
PHPExcel Get data fromDatabase and put value into cells
Need some help... So, i'm trying to export data from database to excel file. I'm able to fetch data to database,but when i'm exporting it to excel inside the while loop I only got one record. Please help.I'm using PHPExcel 1.8.0 libray Here is my code: <?php include('config/config_msdb.php'); /** Set default timezone (will throw a notice otherwise) */ date_default_timezone_set('Asia/Manila'); // include PHPExcel require('lib/PHPExcel.php'); // create new PHPExcel object $objPHPExcel = new PHPExcel; // set default font $objPHPExcel->getDefaultStyle()->getFont()->setName('Calibri'); // set default font size $objPHPExcel->getDefaultStyle()->getFont()->setSize(10); // create the writer $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007"); /** * Define currency and number format. */ // currency format, € with < 0 being in red color $currencyFormat = '#,#0.## \€;[Red]-#,#0.## \€'; // number format, with thousands separator and two decimal points. $numberFormat = '#,#0.##;[Red]-#,#0.##'; // writer already created the first sheet for us, let's get it $objSheet = $objPHPExcel->getActiveSheet(); // rename the sheet $objSheet->setTitle('YellowCab'); // let's bold and size the header font and write the header // as you can see, we can specify a range of cells, like here: cells from A1 to A4 $objSheet->getStyle('A2:P2')->getFont()->setBold(true)->setSize(12); // write header $objSheet->getCell('A2')->setValue('Date'); $objSheet->getCell('B2')->setValue('TC Within 30 mins'); $objSheet->getCell('C2')->setValue('Total TC'); $objSheet->getCell('D2')->setValue('%'); $objSheet->getCell('E2')->setValue("Within 15 mins"); $objSheet->getCell('F2')->setValue("Total TC"); $objSheet->getCell('G2')->setValue("%"); $objSheet->getCell('H2')->setValue("Excellent TC"); $objSheet->getCell('I2')->setValue("Total TC"); $objSheet->getCell('J2')->setValue("%"); $objSheet->getCell('K2')->setValue('Good TC'); $objSheet->getCell('L2')->setValue('Total TC'); $objSheet->getCell('M2')->setValue('%'); $objSheet->getCell('N2')->setValue('Poor TC'); $objSheet->getCell('O2')->setValue('Total TC'); $objSheet->getCell('P2')->setValue('%'); //get record $query="SELECT pr.TransDate,pr.TC30,pr.Total_TRX1,cast(round(pr.Hitrate,0) as nvarchar (10))+'%' AS Hitrate ,pr.PDT15,pr.Total_TRX2,cast(round(pr.ProdTime,0) as nvarchar(10))+'%' AS ProdTime,pr.Excellence,pr.Total_TRX4, cast(round(pr.ExcelPercent,0) as nvarchar(10))+'' AS ExcelPercent,pr.Good,pr.Total_TRX5,cast(round(pr.GoodPercent,0) as nvarchar(10))+'%' AS GoodPercent, pr.Poor,pr.Total_TRX6,cast(round(pr.PoorPercent,0) as nvarchar(10))+'%' AS PoorPercent,lp.area_name FROM part_view AS pr LEFT JOIN lp_areas AS lp ON lp.id = pr.StoreID WHERE lp.is_delete=0 AND lp.area_status=1 AND lp.id!='43' ORDER BY pr.TransDate DESC"; $que = mssql_query($query); $i = '3'; while($row=mssql_fetch_array($que)){ $transdate=date('Y-m-d',strtotime($row["TransDate"])); $tc30=$row["TC30"]; $totaltrx1=$row["Total_TRX1"]; $hitrate=$row["Hitrate"]; $pdt15=$row["PDT15"]; $totaltrx2=$row["Total_TRX2"]; $prodtime=$row["ProdTime"]; $excellence=$row["Excellence"]; $totaltrx4=$row["Total_TRX4"]; $excelpercent=$row["ExcelPercent"]; $good=$row["Good"]; $totaltrx5=$row["Total_TRX5"]; $goodpercent=$row["GoodPercent"]; $poor=$row["Poor"]; $totaltrx6=$row["Total_TRX6"]; $poorpercent=$row["PoorPercent"]; $storename=$row["area_name"]; // we could get this data from database, but here we are writing for simplicity $objSheet->getCell('A'.$i.'')->setValue($transdate); $objSheet->getCell('B'.$i.'')->setValue($tc30); $objSheet->getCell('C'.$i.'')->setValue($totaltrx1); $objSheet->getCell('D'.$i.'')->setValue($hitrate); $objSheet->getCell('E'.$i.'')->setValue($pdt15); $objSheet->getCell('F'.$i.'')->setValue($totaltrx2); $objSheet->getCell('G'.$i.'')->setValue($prodtime); $objSheet->getCell('H'.$i.'')->setValue($excellence); $objSheet->getCell('I'.$i.'')->setValue($totaltrx4); $objSheet->getCell('J'.$i.'')->setValue($excelpercent); $objSheet->getCell('K'.$i.'')->setValue($good); $objSheet->getCell('L'.$i.'')->setValue($totaltrx5); $objSheet->getCell('M'.$i.'')->setValue($goodpercent); $objSheet->getCell('N'.$i.'')->setValue($poor); $objSheet->getCell('O'.$i.'')->setValue($totaltrx6); $objSheet->getCell('P'.$i.'')->setValue($poorpercent); $i++; // autosize the columns $objSheet->getColumnDimension('A')->setAutoSize(true); $objSheet->getColumnDimension('B')->setAutoSize(true); $objSheet->getColumnDimension('C')->setAutoSize(true); $objSheet->getColumnDimension('D')->setAutoSize(true); $objSheet->getColumnDimension('E')->setAutoSize(true); $objSheet->getColumnDimension('F')->setAutoSize(true); $objSheet->getColumnDimension('G')->setAutoSize(true); $objSheet->getColumnDimension('H')->setAutoSize(true); $objSheet->getColumnDimension('I')->setAutoSize(true); $objSheet->getColumnDimension('J')->setAutoSize(true); $objSheet->getColumnDimension('K')->setAutoSize(true); $objSheet->getColumnDimension('L')->setAutoSize(true); $objSheet->getColumnDimension('M')->setAutoSize(true); $objSheet->getColumnDimension('N')->setAutoSize(true); $objSheet->getColumnDimension('O')->setAutoSize(true); $objSheet->getColumnDimension('P')->setAutoSize(true); //Setting the header type header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="file.xlsx"'); header('Cache-Control: max-age=0'); $objWriter->save('php://output'); /* If you want to save the file on the server instead of downloading, replace the last 4 lines by $objWriter->save('test.xlsx'); */ }//end get rows ?> Thanks in advance
Just to update I have successfully exported all data fetched from my database. So here is my solution: $i = '3'; while($row=mssql_fetch_array($que)){ $transdate=date('Y-m-d',strtotime($row["TransDate"])); $tc30=$row["TC30"]; $totaltrx1=$row["Total_TRX1"]; $hitrate=$row["Hitrate"]; $pdt15=$row["PDT15"]; $totaltrx2=$row["Total_TRX2"]; $prodtime=$row["ProdTime"]; $excellence=$row["Excellence"]; $totaltrx4=$row["Total_TRX4"]; $excelpercent=$row["ExcelPercent"]; $good=$row["Good"]; $totaltrx5=$row["Total_TRX5"]; $goodpercent=$row["GoodPercent"]; $poor=$row["Poor"]; $totaltrx6=$row["Total_TRX6"]; $poorpercent=$row["PoorPercent"]; $storename=$row["area_name"]; $data[] = array( 'TransDate'=>$transdate, 'TC30'=>$tc30, 'Total_TRX1'=>$totaltrx1, 'Hitrate'=>$hitrate, 'PDT15'=>$pdt15, 'Total_TRX2'=>$totaltrx2, 'ProdTime'=>$prodtime, 'Excellent'=>$excellent, 'Total_TRX4'=>$totaltrx4, 'ExcelPercent'=>$excelpercent, 'Good'=>$good, 'Total_TRX5'=>$totaltrx5, 'GoodPercent'=>$goodpercent, 'Poor'=>$poor, 'Total_TRX6'=>$totaltrx6, 'PoorPercent'=>$poorpercent ); } $array = stripslashes(json_encode($data)); $json = (object)json_decode($array); foreach($json AS $datas){ $objSheet->getCell('A'.$i.'')->setValue($datas->TransDate); $objSheet->getCell('B'.$i.'')->setValue($datas->TC30); $objSheet->getCell('C'.$i.'')->setValue($datas->Total_TRX1); $objSheet->getCell('D'.$i.'')->setValue($datas->Hitrate); $objSheet->getCell('E'.$i.'')->setValue($datas->PDT15); $objSheet->getCell('F'.$i.'')->setValue($datas->Total_TRX2); $objSheet->getCell('G'.$i.'')->setValue($datas->ProdTime); $objSheet->getCell('H'.$i.'')->setValue($datas->Excellence); $objSheet->getCell('I'.$i.'')->setValue($datas->Total_TRX4); $objSheet->getCell('J'.$i.'')->setValue($datas->ExcelPercent); $objSheet->getCell('K'.$i.'')->setValue($datas->Good); $objSheet->getCell('L'.$i.'')->setValue($datas->Total_TRX5); $objSheet->getCell('M'.$i.'')->setValue($datas->GoodPercent); $objSheet->getCell('N'.$i.'')->setValue($datas->Poor); $objSheet->getCell('O'.$i.'')->setValue($datas->Total_TRX6); $objSheet->getCell('P'.$i.'')->setValue($datas->PoorPercent); $i++; } Thanks!
file format is incorrect in PHPExcel Code
I am trying to write mySQL data into Exlcel using PHPExcel, but I am getting file format is invalid in my above PHP code using PHPExcel. Can someone please help me to find out what is wrong in code: $query = "SELECT company_id, userid FROM uam_user"; $result = mysql_query($query) or die ("Error in Query".mysql_error()); // Instantiate a new PHPExcel object $objPHPExcel = new PHPExcel(); // Set document properties $objPHPExcel->getProperties()->setCreator("Security Team") ->setLastModifiedBy("System") ->setTitle("System") ->setSubject("System Security") ->setDescription("Non Production user Upload Data") ->setKeywords("User Upload") ->setCategory("Security"); // Set the active Excel worksheet to sheet 0 $objPHPExcel->setActiveSheetIndex(0); $objPHPExcel->getActiveSheet()->SetCellValue("A1", 'company_id'); $objPHPExcel->getActiveSheet()->SetCellValue("B2", 'userid'); //start of printing column names as names of MySQL fields $rowCount = 2; //$num_rows = mysql_num_rows($result); //echo $num_rows; $i = 0; while($row = mysql_fetch_array($result, MYSQL_ASSOC)){ if ($row['userid'] != '') { //echo "A$rowCount=".$row['company_id']."|B$rowCount=".$row['userid']."<br>"; $objPHPExcel->getActiveSheet()->SetCellValue("A$rowCount",$row['company_id']); $objPHPExcel->getActiveSheet()->SetCellValue("B$rowCount",$row['userid']); } $rowCount++; //echo $rowCount; } $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="item_list.xlsx"'); header('Cache-Control: max-age=0'); ob_end_clean(); $objWriter->save ( 'php://output' );
Wordpress hook write to database before post save
I am beginner in wordpress and i would like to ask some help. I need some hook , which will split the post after some number of characters (lets say 300) and will add my text after each split.I created filter hook, but i do not know how to create action hook - to write splitted text with my text to database before save,publish or edit action. This code works , but how to save to database? function inject_ad_text_after_n_chars($content) { $enable_length = 30; global $_POST; if (is_single() && strlen($content) > $enable_length) { $before_content = substr($content, 0, 30); $before_content2 = substr($content, 30, 30); $before_content3 = substr($content, 60, 30); $before_content4 = substr($content, 90, 30); $texta = '00000000000000000000'; return $before_content . $texta . $before_content2 . $texta . $before_content3 . $texta . $before_content4; } else { return $content; } } add_filter('the_content', 'inject_ad_text_after_n_chars');
You are looking for wp_insert_post_data filter. In this function, to parameter is supplied for you to filter the data before it is inserted. You can use it like - add_filter('wp_insert_post_data', 'mycustom_data_filter', 10, 2); function mycustom_data_filter($filtered_data, $raw_data){ // do something with the data, ex // For multiple occurence $chunks = str_split($filtered_data['post_content'], 300); $new_content = join('BREAK HERE', $chunks); // For single occurence $first_content = substr($filtered_data['post_content'], 0, 300); $rest_content = substr($filtered_data['post_content'], 300); $new_content = $first_content . 'BREAK HERE' . $rest_content; // put into the data $filtered_data['post_content'] = $new_content; return $filtered_data; }
FullCalendar with JSON feed loading slowly
I'm using FullCalendar to load events from custom post types on WP, through a JSON feed. It's working, but it's taking some time to load. Please check here: http://cea3.iscte.pt/en/agenda-3/ (june or august). Do any of you have a clue what can be causing it? This is the full code for the JSON feed: <?php // - standalone json feed - header('Content-Type:application/json'); // - grab wp load, wherever it's hiding - if(file_exists('../../../../wp-load.php')) : include '../../../../wp-load.php'; else: include '../../../../../wp-load.php'; endif; global $wpdb; // - grab date barrier - $oneyear = strtotime('-1 year') + ( get_option( 'gmt_offset' ) * 3600 ); // - query - global $wpdb; $querystr = " SELECT * FROM $wpdb->posts wposts, $wpdb->postmeta metastart, $wpdb->postmeta metaend WHERE (wposts.ID = metastart.post_id AND wposts.ID = metaend.post_id) AND (metaend.meta_key = 'tf_events_enddate' AND metaend.meta_value > $oneyear ) AND metastart.meta_key = 'tf_events_enddate' AND wposts.post_type = 'tf_events' AND wposts.post_status = 'publish' ORDER BY metastart.meta_value ASC LIMIT 500 "; $events = $wpdb->get_results($querystr, OBJECT); $jsonevents = array(); // - loop - if ($events): global $post; foreach ($events as $post): setup_postdata($post); // - custom variables - $custom = get_post_custom(get_the_ID()); $sd = $custom["tf_events_startdate"][0]; $ed = $custom["tf_events_enddate"][0]; // - grab gmt for start - $gmts = date('Y-m-d H:i:s', $sd); $gmts = get_gmt_from_date($gmts); // this function requires Y-m-d H:i:s $gmts = strtotime($gmts); // - grab gmt for end - $gmte = date('Y-m-d H:i:s', $ed); $gmte = get_gmt_from_date($gmte); // this function requires Y-m-d H:i:s $gmte = strtotime($gmte); // - set to ISO 8601 date format - $stime = date('c', $gmts); $etime = date('c', $gmte); $thetitle = $post->post_title; $short_title = substr($thetitle,0,50); $eventpostid = $post->ID; $eventslug = wp_get_post_terms( $eventpostid, 'tf_eventcategory' ); $eventvenueslug = $eventslug[0]->slug; $tf_events_link = get_post_meta($post->ID, 'tf_events_link', true); $tf_events_permalink = get_permalink($post->ID); if ($tf_events_link) { $url_event = $tf_events_link ; } else { $url_event = $tf_events_permalink; }; // - json items - $jsonevents[]= array( 'title' => $short_title . '...', 'allDay' => false, // <- true by default with FullCalendar 'start' => $stime, 'end' => $etime, 'url' => $url_event, 'className' => $eventvenueslug ); endforeach; else : endif; // - fire away - echo json_encode($jsonevents); ?> Thank you.
It does seem like it takes a few seconds to load. I use this calendar and it takes about 2-6 seconds to load- The longest was 6 seconds but i had about 3 sources and ~40 events. Now I am not sure if that for you is a long time because you did not specify how long it actaully takes. It looks like the call is on the same server so the only problem can be the SQL that takes long to reply. Is it dedicated or shared server? Your PHP looks fine and should execute quickly. I have similar logic using .NET and SQL Server. This is the time it takes to load your calendar from my side of the world. The only other way to speed it up is to use Caching http://arshaw.com/fullcalendar/docs/event_data/events_json_feed/#options and manage it to reload the source somehow with a clever check of the date? or something. I am sure the times would be reduced to ms once the feed has been loaded before. You would have to do something clever like load the current month quickly - and in the background load 1 year or 2 years and cache it. Then when you change months it will be instant because its in memory.