PHPExcel生成表格简单实例讲解

2023-09-05 15:31:47 浏览数 (3)

phpexcel

DEMO代码如下(PHPExcel下载地址):

代码语言:javascript复制
<?php

require_once './PHPExcel-1.8.1/Classes/PHPExcel.php';

//创建对象
$excel = new PHPExcel();

//Excel表格式,这里简略写了8列,必须大于等于表头元素个数
$letter = array('A','B','C','D','E','F','F','G');

//表头数组
$tableheader = array('学号','姓名','性别','年龄','班级');

//填充表头信息
for ($i = 0;$i < count($tableheader);$i  ) {
    $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
}

//表格数组
$data = array(
    array('1','小王','男','20','100'),
    array('2','小李','男','20','101'),
    array('3','小张','女','20','102'),
    array('4','小赵','女','20','103')
);

//填充表格信息
for ($i = 2;$i <= count($data)   1;$i  ) {
$j = 0;
    foreach ($data[$i - 2] as $key=>$value) {
        $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
        $j  ;
    }
}

//创建Excel输入对象
$write = new PHPExcel_Writer_Excel2007($excel);
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl");
header("Content-Type:application/octet-stream");
header('Content-Disposition:attachment;filename="成绩-' . date('Y-m-d') . '.xlsx"'); //文件名
header("Content-Transfer-Encoding:binary");
$write->save('php://output');

//指定保存位置
//$write->save('./xxx.xlsx');

以下代码为另一种遍历方式(博主的项目代码):

代码语言:javascript复制
<?php

// $actions 形如 array[0=>obj{$key=>$val},1=>obj{$key=>$val}]
require_once '../PHPExcel-1.8.1/Classes/PHPExcel.php';

//创建对象
$excel = new PHPExcel();

//Excel表格式,这里简略写了8列,必须大于等于表头元素个数
$letter = array('A','B','C','D','E','F','F','G');

//表头数组
$tableheader = array('日期','操作者','动作','对象类型','ID', '对象名称');

  //循环填充表头信息
  for ($i = 0;$i < count($tableheader);$i  ) {
      $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
  }

  //循环填充表格信息(这里是与上面的主要不同之处,有助于理解setCellValue的机制,我偷个懒随便改改就复制粘贴上来了)
  for ($k = 0; $k < count($actions); $k  ) {
      $excel->getActiveSheet()->setCellValue("A" . strval($k   2), $actions[$k]->date);
      $excel->getActiveSheet()->setCellValue("B" . strval($k   2), $actions[$k]->actor);
      $excel->getActiveSheet()->setCellValue("C" . strval($k   2), $actions[$k]->actionLabel);
      $excel->getActiveSheet()->setCellValue("D" . strval($k   2), $actions[$k]->objectType]);
      $excel->getActiveSheet()->setCellValue("E" . strval($k   2), $actions[$k]->objectID);
      $excel->getActiveSheet()->setCellValue("F" . strval($k   2), $actions[$k]->objectName);
  }

//创建Excel输入对象
$write = new PHPExcel_Writer_Excel2007($excel);
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl");
header("Content-Type:application/octet-stream");
header('Content-Disposition:attachment;filename="动态-' . date('Y-m-d') . '.xlsx"');
header("Content-Transfer-Encoding:binary");
$write->save('php://output');

//指定保存位置
//$write->save('./xxx.xlsx');

0 人点赞