用类库封装:
<?php
/**
* Created by PhpStorm.
* User: Houis
* Date: 18/3/29
* Time: 下午2:44
*/
class Excel_library
{
private $firstCell;
private $cellKey = array(
'A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM',
'AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ'
);
private $otherCell = [];
/**
* Constructor
*/
public function __construct()
{
include_once 'PHPExcel/Classes/PHPExcel.php';
include_once 'PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';
}
/**
* @param $title
* 设置表格第一行数组
*/
public function setFirstCell($firstCell){
$this->firstCell = $firstCell;
}
/**
* @param $otherCell
* 设置表格数组
*/
public function setOtherCell($otherCell){
$this->otherCell = $otherCell;
}
public function export($fileName){
$excel = new PHPExcel();
//填充表头信息
$this->setExcelFristCell($excel);
//填充表格信息
$this->setExcelOtherCell($excel);
//创建Excel输入对象
$write = new PHPExcel_Writer_Excel5($excel);
header("Pragma: public");
header("Expires: 0");
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-Type:application/download");;
header('Content-Disposition:attachment;filename="'.$fileName.'.xls"');
header("Content-Transfer-Encoding:binary");
$write->save('php://output');
}
/**
* @param $obj
* 写入Excel第一行数据
*/
private function setExcelFristCell($obj){
for($i = 0;$i < count($this->firstCell);$i++) {
$obj->getActiveSheet()->setCellValue($this->cellKey[$i]."1",$this->firstCell[$i]);
}
}
/**
* @param $obj
* 写入Excel第一行以外的数组
*/
private function setExcelOtherCell($obj){
for ($i = 2;$i <= count($this->otherCell) + 1;$i++) {
$j = 0;
foreach ($this->otherCell[$i - 2] as $key=>$value) {
$obj->getActiveSheet()->setCellValue($this->cellKey[$j].$i,"$value");
$j++;
}
}
}
}
controller调用:
public function exportExcelTest(){
$this->load->library('excel_library');
$cellName = array('a','b','c','d','e');
$data = array(
array('1','小王','男','20','100'),
array('2','小李','男','20','101'),
array('3','小张','女','20','102'),
array('4','小赵','女','20','103')
);
$this->excel_library->setFirstCell($cellName);
$this->excel_library->setOtherCell($data);
$this->excel_library->export('demo');
}