用phpexcel怎么导出excel文件
发布网友
发布时间:2022-04-09 11:51
我来回答
共1个回答
热心网友
时间:2022-04-09 13:20
下载phpexcel类库 代码如下:
<?php
require_once('PHPExcel.php');
require_once('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 = $iofactory -> createWriter($objPHPExcel, 'Excel2007');
$objWriter -> save('SetExcelName.xlsx');
//导出代码
// $objPHPExcel->getActiveSheet() -> setTitle('SetExcelName');
// $objPHPExcel-> setActiveSheetIndex(0);
// $objWriter = $iofactory -> createWriter($objPHPExcel, 'Excel2007');
// $filename = 'SetExcelName.xlsx';
// header('Content-Type: application/vnd.ms-excel');
// header('Content-Type: application/octet-stream');
// header('Content-Disposition: attachment; filename="' . $filename . '"');
// header('Cache-Control: max-age=0');
// $objWriter -> save('php://output');
?>