Alex的博客

本博客的文章均为原创,是本人从事行业多年来所遇见一些小问题的解决心得,希望可以帮助到大家!



phpexcel 导出表格

下载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');
?>
浏览652  评论0  Alex于 2016-9-30 11:34
发言