CExcel.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /**
  3. * FecShop file.
  4. *
  5. * @link http://www.fecshop.com/
  6. * @copyright Copyright (c) 2016 FecShop Software LLC
  7. * @license http://www.fecshop.com/license/
  8. */
  9. namespace fec\helpers;
  10. use Yii;
  11. /**
  12. * @author Terry Zhao <2358269014@qq.com>
  13. * @since 1.0
  14. */
  15. class CExcel
  16. {
  17. # 1.加载phpExcel组件文件
  18. public static function prepare(){
  19. require_once(__DIR__."/../lib/PHPExcel/PHPExcel.php");
  20. require_once(__DIR__."/../lib/PHPExcel/PHPExcel/IOFactory.php");
  21. require_once(__DIR__."/../lib/PHPExcel/PHPExcel/Reader/Excel2007.php");
  22. }
  23. # 2.得到excel文件的内容
  24. public static function getExcelContent($xlsDir){
  25. self::prepare();
  26. //echo $xlsDir;exit;
  27. $objPHPExcel = \PHPExcel_IOFactory::load($xlsDir);
  28. $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
  29. return $sheetData;
  30. }
  31. # 3.array中的数据,以excel的方式下载下来。
  32. # $data 是数据数组
  33. # $fileName 是文件名字
  34. /*
  35. 参数说明
  36. $data = [
  37. [11,22,33,44],
  38. [131,22,33,44],
  39. ];
  40. 使用方式:\fec\helpers\CExcel::downloadExcelFileByArray($data);
  41. 调用这个方法后,会下载excel文件。
  42. */
  43. public static function downloadExcelFileByArray($data,$fileName=''){
  44. self::prepare();
  45. if(!$fileName){
  46. $fileName = 'xls-download-'.date('Y-m-d-H-i-s').'.xls';
  47. }
  48. $objPHPExcel = new \PHPExcel();
  49. $objPHPExcel->getActiveSheet()->fromArray($data);
  50. $objPHPExcel->getActiveSheet()->freezePane('A2');
  51. // Redirect output to a client’s web browser (Excel5)
  52. header('Content-Type: application/vnd.ms-excel');
  53. header('Content-Disposition: attachment;filename="'.$fileName.'"');
  54. header('Cache-Control: max-age=0');
  55. // If you're serving to IE 9, then the following may be needed
  56. header('Cache-Control: max-age=1');
  57. // If you're serving to IE over SSL, then the following may be needed
  58. header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  59. header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  60. header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  61. header ('Pragma: public'); // HTTP/1.0
  62. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  63. $objWriter->save('php://output');
  64. exit;
  65. }
  66. }