<?php
/*php生成excel完整实例代码
现求:php生成excel完整实例代码
最好能说明如何调用!谢谢
java_sunhui4 | 浏览 8131 次 2014-09-24 14:50
2014-09-25 11:15
最佳答案
下载phpexcel类库 代码如下:*/
include 'PHPExcel/PHPExcel.php' ;
//include 'PHPExcel/PHPExcel/IOFactory.php';
$objPHPExcel=new PHPExcel();
//$iofactory=new IOFactory();
//获得数据 ---一般是从数据库中获得数据
$data=array(
0=>array('id'=>2013,'name'=>'张某某','age'=>21),
1=>array('id'=>201,'name'=>'EVA','age'=>21)
);
//设置excel列名
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1','编号');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B1','姓名');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('C1','年龄');
//把数据循环写入excel中
foreach($data as $key => $value){
$key+=2;
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$key,$value['id']);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$key,$value['name']);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$key,$value['age']);
}
//excel保存在根目录下 如要导出文件,以下改为注释代码
$objPHPExcel->getActiveSheet() -> setTitle('SetExcelName');
$objPHPExcel-> setActiveSheetIndex(0);
// $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//ob_end_clean();
header("Content-Type: application/vnd.ms-excel;");
/*header("Content-Disposition:attachment;filename=5kcrm_user_".date('Y-m-d',mktime()).".xls");*/
header("Pragma:no-cache");
header("Expires:0");
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
第二种方法
vendor('PHPExcel.Classes.PHPExcel');
//创建对象
$excel = new \PHPExcel();
//Excel表格式,这里简略写了8列
$letter = array('A','B','C','D','E','F','G');
//表头数组
$tableheader = array(a,b,c,d,e,f,g);
//定义导出的文件名
$filename = date('Y-m-d',time());
//date('Y-m-d',$sdate).$lesson.$lid;
//填充表头信息
for($i = 0;$i < count($tableheader);$i++) {
$excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
}
//表格数组
$data = array(
array('1','小王','男'),
array('2','小李','男'),
array('3','小张','女'),
array('4','小赵','女')
);
//填充表格信息
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_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');
//转换数组格式
for($i=0;$i <count($data);$i++){
$dd[$i]=array($data[$i]['id'],$data[$i]['member_mark'],$data[$i]['name'],$data[$i]['password'],$data[$i]['mobile'],$data[$i]['money'],$data[$i]['rank'],$data[$i]['add_time'],$data[$i]['update_time']);
}