phpexcel圖形圖表(一)入門


PHPExcel - Excel的PHP處理引擎

PHPExcel 提供了一系列的 PHP語言 類,讓你可以輕松地讀寫操作以下格式的文件:.xls/.xlsx/.csv/.ods/Gnumeric/PDF/HTML...
主要功能包括:設置文件的meta信息,多工作表,定制字體和樣式,邊框和填充,圖片,計算公式,轉換文件類型等等

之前我只是用到了導出數據到列表格式的Excel文件,這次需要實現的目標是:JSON->phpexcel->excel+chart(line/pie/etc...)

本系列《phpexcel圖形圖表》文章梗概如下:

phpexcel圖形圖表(一)-入門----------------介紹PHPExcel類庫和畫圖的基本步驟
phpexcel圖形圖表(二)-圖形----------------以最常用的line/pie/bar/radar圖形為例作圖,並對比和分析4種API
phpexcel圖形圖表(三)-進階----------------讓圖形美化,完成一些高級的效果
phpexcel圖形圖表(三)-高級----------------PHPExcel能完成的圖表相關的高級功能

原創文章,轉載請注明出處:http://www.cnblogs.com/phpgcs

本篇文章梗概:
1. 下載並研究PHPExcel倉庫
2. PHPExcel畫圖和普通數據處理的區別
3. 注意事項總結

phpgcs.com

phpgcs
首先最好是把PHPExcel的項目下載到本地來研究

git clone git@github.com:PHPOffice/PHPExcel.git

請先仔細閱讀README.md說明文檔,因為里面包含了很重要的版本信息,尤其是讀寫Excel文檔的版本范圍信息

### Reading
 * BIFF 5-8 (.xls) Excel 95 and above
 * Office Open XML (.xlsx) Excel 2007 and above
 * SpreadsheetML (.xml) Excel 2003
 * Open Document Format/OASIS (.ods)
 * Gnumeric
 * HTML
 * SYLK
 * CSV

### Writing
 * BIFF 8 (.xls) Excel 95 and above
 * Office Open XML (.xlsx) Excel 2007 and above
 * HTML
 * CSV
 * PDF (using either the tcPDF, DomPDF or mPDF libraries, which need to be installed separately)


## Requirements
 * PHP version 5.2.0 or higher
 * PHP extension php_zip enabled (required if you need PHPExcel to handle .xlsx .ods or .gnumeric files)
 * PHP extension php_xml enabled
 * PHP extension php_gd2 enabled (optional, but required for exact column width autocalculation)

  

進入Examples文件夾,OhMygod,可以完成這么多的功能呀

01pharSimple.php
01simple-download-pdf.php
01simple-download-xls.php
01simple-download-xlsx.php
01simplePCLZip.php
01simple.php
02types.php
02types-xls.php
03formulas.php
04printing.php
05featuredemo.inc.php
05featuredemo.php
06largescale.php
06largescale-with-cellcaching.php
06largescale-with-cellcaching-sqlite3.php
06largescale-with-cellcaching-sqlite.php
06largescale-xls.php
07readerPCLZip.php
07reader.php
08conditionalformatting2.php
08conditionalformatting.php
09pagebreaks.php
10autofilter.php
10autofilter-selection-1.php
10autofilter-selection-2.php
10autofilter-selection-display.php
11documentsecurity.php
11documentsecurity-xls.php
12cellProtection.php
13calculation.php
14excel5.php
15datavalidation.php
15datavalidation-xls.php
16csv.php
17html.php
18extendedcalculation.php
19namedrange.php
20readexcel5.php
21pdf.php
22heavilyformatted.php
23sharedstyles.php
24readfilter.php
25inmemoryimage.php
26utf8.php
27imagesexcel5.php
28iterator.php
29advancedvaluebinder.php
30template.php
31docproperties_write.php
31docproperties_write-xls.php
32chartreadwrite.php
33chartcreate-area.php
33chartcreate-bar.php
33chartcreate-bar-stacked.php
33chartcreate-column-2.php
33chartcreate-column.php
33chartcreate-composite.php
33chartcreate-line.php
33chartcreate-multiple-charts.php
33chartcreate-pie.php
33chartcreate-radar.php
33chartcreate-scatter.php
33chartcreate-stock.php
34chartupdate.php
35chartrender.php
36chartreadwriteHTML.php
36chartreadwritePDF.php
37page_layout_view.php
38cloneWorksheet.php
40duplicateStyle.php
Excel2003XMLReader.php
Excel2003XMLTest.xml
.gitignore
GnumericReader.php
GnumericTest.gnumeric
images/
list
.~lock.33chartcreate-line.xlsx#
OOCalcReaderPCLZip.php
OOCalcReader.php
OOCalcTest.ods
Quadratic2.php
Quadratic.php
Quadratic.xlsx
runall.php
SylkReader.php
SylkTest.slk
templates/
XMLReader.php
XMLTest.xml

 

好吧,這次的任務是chart,就先從 line chart 入手,相關的文件只有一個 ***line.php

我們先直接運行一把:

liuyuan@ebuinfo:/var/www/projects/PHPExcel/Examples$ php 33chartcreate-line.php 
07:13:22 Write to Excel2007 format
07:13:23 File written to 33chartcreate-line.xlsx
07:13:23 Peak memory usage: 8.75 MB
07:13:23 Done writing file
File has been created in /var/www/projects/PHPExcel/Examples

  

Wow,生成了一個Excel文件哦,趕緊打開

phpexcel,chart,phpgcs

 

這也太簡單了吧,趕緊看看源碼(附帶說明)

<?php

/** 開啟各種PHP Error Report機制 */
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類庫的入口文件 */
require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';

/* 創建PHPExcel對象 */
$objPHPExcel = new PHPExcel();

/* 其實最常用的操作是Excel的工作表sheet,因此我們取活動sheet對象 */
$objWorksheet = $objPHPExcel->getActiveSheet();

/* 畫一個line圖的源數據是一個2維數組,這樣可以畫多條line,即多個series */
$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),
	)
);

/* 這里有一個重要的類PHPExcel_Chart_DataSeriesValues,后面多次用到,它有幾個參數
 *
 * 數據類型  Datatype
 * 指定單元格  Cell reference for data
 * 格式代碼 Format Code
 * 本系列數據中元素個數  Number of datapoints in series
 * Data values
 * Data
*/

// 設置每一個data series 數據系列的名稱
$dataseriesLabels = array(
	new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1),	//	2010
	new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1),	//	2011
	new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1),	//	2012
);
//	設置X軸Tick數據(X軸每一個刻度值)
$xAxisTickValues = array(
	new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$A$2:$A$5', NULL, 4),	//	Q1 to Q4
);
//	設置作圖區域數據
$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),
);

//	構建數據系列 dataseries
$series = new PHPExcel_Chart_DataSeries(
	PHPExcel_Chart_DataSeries::TYPE_LINECHART,		// plotType
	PHPExcel_Chart_DataSeries::GROUPING_STACKED,	// plotGrouping
	range(0, count($dataSeriesValues)-1),			// plotOrder
	$dataseriesLabels,								// plotLabel
	$xAxisTickValues,								// plotCategory
	$dataSeriesValues								// plotValues
);

// 給數據系列分配一個做圖區域
$plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_TOPRIGHT, NULL, false);

// 設置圖形標題
$title = new PHPExcel_Chart_Title('Test Stacked Line Chart');
// 設置Y軸標簽
$yAxisLabel = new PHPExcel_Chart_Title('Value ($k)');


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

// 設置圖形繪制區域
$chart->setTopLeftPosition('A7');
$chart->setBottomRightPosition('H20');

// 將圖形添加到當前工作表
$objWorksheet->addChart($chart);


// 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;

  

總結一下:

1,引入PHPExcel
2,填充源數據到工作表上
	$objWorkSheet->fromArray($array);
	or
	$objWorkSheet->setCellValues('A1', 1);
3,設置dataseries
	PHPExcel_Chart_DataSeries::TYPE_LINECHART,
	PHPExcel_Chart_DataSeries::GROUPING_STACKED,
	range(0, count($dataSeriesValues)-1),
	$dataseriesLabels=>array(new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$AB$1', NULL, 1)),
	$xAxisTickValues=>array(new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$AA$2:$AA$21', NULL, 20),),
	$dataSeriesValues=>array(new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$AB$2:$AB$21', NULL, 20))
4,設置chart
	'chartTitle'=>'just a title',
	$title=>new PHPExcel_Chart_Title('新聞熱點趨勢'),
	$legend=>new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_TOPRIGHT, NULL, false),
	$plotarea=>new PHPExcel_Chart_PlotArea(NULL, array($series)),
	'plotVisibleOnly'=>true,
	'displayBlanksAs'=>0,
	'xAxisLabel'=>NULL,
	'yAxisLabel'=>new PHPExcel_Chart_Title('報道量'),
5,設置chart位置
	$chart->setTopLeftPosition('A1');                                                                                                                 
	$chart->setBottomRightPosition('P20');
6,添加chart
    $objWorksheet->addChart($chart);
7,保存文件
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
	$objWriter->setIncludeCharts(TRUE);
	$objWriter->save(str_replace('.php', '.xlsx', __FILE__));

  

很簡單吧,跟PHP導出普通數據對比,就是多了chart的各種設置

仔細想想,其實我們用PHPExcel API 這個設置的過程,跟我們直接在Excel中填充一個二維數組,然后插入圖表的過程進行設置數據區域的過程是一樣的

原創文章,轉載請注明出處:http://www.cnblogs.com/phpgcs

 

 

最重要的2句話是:

普通數據:

$objWorkSheet->setCellValue('A1', 12345);

圖表:我們要先將源數據放到工作表上(可以用setCellValue ,也可以用fromArray),然后做圖的時候調用這些數據所在的位置  

$xAxisTickValues = array(
        new PHPExcel_Chart_DataSeriesValues('String', '圖表分析!$AE$2:$AE$30', NULL, 30),
);

  

有幾點需要注意的是:

1,保存文件的格式 xlsx 以及 PHPExcel_IOFactory 調用的是 'Excel2007' 而不能是 'Excel5'  

$filename = date('Y-m-d', time()).'_'.md5(time()).'.xlsx';
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); 

  

另外只要是有chart,千萬不能少了2行代碼:

$objWorksheet->addChart($chart4);

$objWriter->setIncludeCharts(TRUE);

  

2,調試的時候,如果報錯

Call to a member function cellExists() on a non-object /phpexcel/Classes/PHPExcel/Calculation.php on line 3241

一般都是 getCellValue()失敗, 請參看那篇blog

 

3,PHPExcel_Chart_DataSeriesValues的第4個參數,是系列數據的個數,要等於確實存在的數據個數,如果開始不知道動態數據會填充幾行,那就用變量,否則圖形會有很多地方是無數據的狀態,很不美觀。

之所以這樣,因為Excel作圖本來就是根據你指定的數據區域作圖的,如果你指定了空的區域,那圖形上也會表現出來的。

$dataSeriesValues = array(
    new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$AB$2:$AB$21', NULL, 20),
 );

  

最后研究下如何數據來源是JSON的情況,其實不就是JSON-->Array

 

$arraydata = json_decode($jsondata, true);
if($jsondata && $arraydata['status'] == 'success')
{
       $arraydata = $arraydata['series'];
       $newarraydata[] = array('日期', '報道量');
       foreach($arraydata as $k=>$v)
       {
              $newarraydata[] = array($k, $v);
         }
        $objPHPExcel->getActiveSheet()->setTitle('圖表分析');
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $objWorksheet->fromArray($newarraydata, NULL, 'AA1');
.....

  

 

END,下一篇再寫寫幾種常用的chart API

原創文章,轉載請注明出處:http://www.cnblogs.com/phpgcs


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM