PHPExcel 生成图形报表

db.php为数据库操作类, $config为数据库配置,PHPExcel版本为PHPExcel_1.8.0,  PHP代码:

$dir = dirname(__FILE__);

require $dir . "/PHPExcel/db.php";

require $dir . "/PHPExcel/PHPExcel.php";

$object = new PHPExcel();

$db = new db($config);

$objSheet = $object->getActiveSheet();



//生成表格

$array = array(

    array("", "一班", "二班", "三班",),

    array("不及格", 20, 30, 40),

    array("良好", 30, 50, 55),

    array("优秀", 15, 17, 20)

);

$objSheet->fromArray($array);



//取出每个班级成绩的所在列

$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),    //    三班

);



//不及格、良好、优秀所在单元格

$xAxisTickValues = array(

    new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$A$2:$A$5', NULL, 4),    //    A2 to A5

);



//取出每个班级成绩数据的所在列

$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),

);





$series = new PHPExcel_Chart_DataSeries(

    PHPExcel_Chart_DataSeries::TYPE_LINECHART,        // 制图类型

    PHPExcel_Chart_DataSeries::GROUPING_STACKED,    // plotGrouping

    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_TOPRIGHT, NULL, false);



$title = new PHPExcel_Chart_Title('测试制作线性图');

$yAxisLabel = new PHPExcel_Chart_Title('Value ($k)');





//    Create the chart

$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');





$objSheet->addChart($chart);



header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

header('Content-Disposition: attachment;filename="03simple.xlsx"');

header('Cache-Control: max-age=0');



$objWriter = PHPExcel_IOFactory::createWriter($object, 'Excel2007');

$objWriter->setIncludeCharts(TRUE);

$objWriter->save('php://output');

效果图:

你可能感兴趣的:(phpexcel)