PHPExcel制作图表

步骤(chart wizard):

  1. chart type
  2. data range
  3. data series
  4. chart elements

大概就是如上几步。下面是一个示例:

<?php
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';

/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

//创建Excel对象
$objPHPExcel = new PHPExcel();
//获取当前活动的sheet
$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),
    )
);
//设置图例,
$dataSeriesLabels = array(
    new PHPExcel_Chart_DataSeriesValues("String", 'Worksheet!$B$1', null, 1),
    new PHPExcel_Chart_DataSeriesValues("String", 'Worksheet!$C$1', null, 1),
    new PHPExcel_Chart_DataSeriesValues("String", 'Worksheet!$D$1', null, 1),
);
//设置x轴名称
$xAxisTickValues = array(
    new PHPExcel_Chart_DataSeriesValues("String", 'Worksheet!$A$2:$A$5', null, 1),
);

//给每图例中的每 一个数据系列 设置值
$dataSeriesValues = array(
    new PHPExcel_Chart_DataSeriesValues("Number", 'Worksheet!$B$2:$B$5', null, 50),
    new PHPExcel_Chart_DataSeriesValues("Number", 'Worksheet!$C$2:$C$5', null, 50),
    new PHPExcel_Chart_DataSeriesValues("Number", 'Worksheet!$D$2:$D$5', null, 50),
);
//根据图例及图例中的值 构建数图系列
$series = new PHPExcel_Chart_DataSeries(
    PHPExcel_Chart_DataSeries::TYPE_LINECHART,
    PHPExcel_Chart_DataSeries::GROUPING_STANDARD,
    range(0, count($dataSeriesValues) - 1),
    $dataSeriesLabels,
    $xAxisTickValues,
    $dataSeriesValues
);
//以下是为下面建图构造数据

$plotArea = new PHPExcel_Chart_PlotArea(null, array($series));
//$layout = new PHPExcel_Chart_Layout([1,3,5]);
//设置图例的位置,bottom top  topbottom
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_BOTTOM,null, false);
//设置图表标题
$title = new PHPExcel_Chart_Title("测试图表制作");
//设置Y轴标题
$yAxisLabel = new PHPExcel_Chart_Title('Y 轴变化');
//设置X轴标题
$xAxisLabel = new PHPExcel_Chart_Title("X 轴变化");
// 创建图形
$chart = new PHPExcel_Chart(
    'penghui build',
    $title,
    $legend,
    $plotArea,
    true,
    0,
    $xAxisLabel,
    $yAxisLabel
);

//设置图表出现的位置

$chart->setTopLeftPosition("B7");
$chart->setBottomRightPosition("K20");
//将图表添加到指定的worksheet中
$objWorksheet->addChart($chart);
//按照指定的格式生成Excel文件
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");

$objWriter->setIncludeCharts(TRUE);

if (file_exists("C:\Users\Mary\Desktop\demo_1.xlsx")) {
    unlink("C:\Users\Mary\Desktop\demo_1.xlsx");
}
$objWriter->save("C:\Users\Mary\Desktop\demo_1.xlsx");

注意事项:

类的引入路径

行列的定位,字母为大写

    setIncludeCharts(TRUE)必须要写的,加载图表

//将图表添加到指定的worksheet中
$objWorksheet->addChart($chart);

0 条评论
发表一条评论