PHPExcelService.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. <?php
  2. namespace app\common\library;
  3. use crmeb\services\JsonService as Json;
  4. class PHPExcelService
  5. {
  6. //PHPExcel实例化对象
  7. private static $PHPExcel=null;
  8. //表头计数
  9. protected static $count;
  10. //表头占行数
  11. protected static $topNumber = 1;
  12. //表能占据表行的字母对应self::$cellkey
  13. protected static $cells;
  14. //表头数据
  15. protected static $data=[];
  16. //文件名
  17. protected static $title='导出';
  18. //行宽
  19. protected static $where=20;
  20. //行高
  21. protected static $height=50;
  22. //表行名
  23. private static $cellKey = array(
  24. 'A','B','C','D','E','F','G','H','I','J','K','L','M',
  25. 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  26. 'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM',
  27. 'AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ'
  28. );
  29. //设置style
  30. private static $styleArray = array(
  31. 'borders' => array(
  32. 'allborders' => array(
  33. // PHPExcel_Style_Border里面有很多属性,想要其他的自己去看
  34. // 'style' => \PHPExcel_Style_Border::BORDER_THICK,//边框是粗的
  35. // 'style' => \PHPExcel_Style_Border::BORDER_DOUBLE,//双重的
  36. // 'style' => \PHPExcel_Style_Border::BORDER_HAIR,//虚线
  37. // 'style' => \PHPExcel_Style_Border::BORDER_MEDIUM,//实粗线
  38. // 'style' => \PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT,//虚粗线
  39. // 'style' => \PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT,//点虚粗线
  40. 'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
  41. //'color' => array('argb' => 'FFFF0000'),
  42. ),
  43. ),
  44. 'font'=>[
  45. 'bold'=>true
  46. ],
  47. 'alignment'=>[
  48. 'horizontal'=>\PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
  49. 'vertical'=>\PHPExcel_Style_Alignment::VERTICAL_CENTER
  50. ]
  51. );
  52. /**
  53. *初始化PHPExcel类
  54. *@param $data array()
  55. *@param $fun function()
  56. * return
  57. */
  58. private static function initialize($data,$fun){
  59. self::$PHPExcel= new \PHPExcel();
  60. if($fun!==null && is_callable($fun)){
  61. self::$styleArray=$fun();
  62. }
  63. if(!is_array($data)) exit(Json::fail('data 为数组'));
  64. self::$data=$data;
  65. }
  66. /**
  67. *设置字体格式
  68. *@param $title string 必选
  69. * return string
  70. */
  71. public static function setUtf8($title){
  72. return "";
  73. //return iconv('utf-8', 'gb2312', $title);
  74. }
  75. /**
  76. *
  77. * execl数据导出
  78. * @param $list 需要导出的数据 格式和以前的可是一样
  79. * @param $list 也可以为匿名函数 匿名函数参数有 $sheet PHPExcel->getActiveSheet(),self::$topNumber 从第几行设置,$cellkey 行号为数组,self::$cells现在设置的最大行号
  80. *
  81. * 特殊处理:合并单元格需要先对数据进行处理
  82. */
  83. public function setExcelContent($list=null)
  84. {
  85. $sheet=self::$PHPExcel->getActiveSheet();
  86. foreach(self::$data as $key=>$val){
  87. $row=self::$cellKey[$key];
  88. $sheet->getColumnDimension($row)->setWidth(isset($val['w'])?$val['w']:self::$where);
  89. $sheet->setCellValue($row.self::$topNumber,isset($val['name'])?$val['name']:$val);
  90. }
  91. $cellkey=array_slice(self::$cellKey,0,self::$count);
  92. if($list!==null && is_array($list)){
  93. foreach ($cellkey as $k=>$v){
  94. foreach ($list as $key=>$val){
  95. if(isset($val[$k]) && !is_array($val[$k])){
  96. $sheet->setCellValue($v.(self::$topNumber+1+$key),$val[$k]);
  97. }else if(isset($val[$k]) && is_array($val[$k])){
  98. $str='';
  99. foreach ($val[$k] as $value){
  100. $str.=$value.chr(10);
  101. }
  102. $sheet->setCellValue($v.(self::$topNumber+1+$key),$str);
  103. }
  104. }
  105. }
  106. $sheet->getDefaultRowDimension()->setRowHeight(self::$height);
  107. //设置边框
  108. $sheet->getStyle('A1:'.self::$cells.(count($list)+self::$topNumber))->applyFromArray(self::$styleArray);
  109. //设置自动换行
  110. $sheet->getStyle('A4:'.self::$cells.(count($list)+self::$topNumber))->getAlignment()->setWrapText(true);
  111. }else if($list!==null && is_callable($list)){
  112. $list($sheet,self::$topNumber,$cellkey,self::$cells)->applyFromArray(self::$styleArray);
  113. }
  114. return $this;
  115. }
  116. /**
  117. * 保存表格数据,并下载
  118. * @param
  119. * @return
  120. */
  121. public function ExcelSave(){
  122. error_reporting(0);
  123. $objWriter=\PHPExcel_IOFactory::createWriter(self::$PHPExcel,'Excel2007');
  124. $filename=self::$title.'--'.time().'.xlsx';
  125. ob_end_clean();
  126. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  127. header('Content-Type: application/vnd.ms-excel');
  128. header('Content-Type: application/octet-stream');
  129. header('Content-Disposition: attachment; filename="' . $filename . '"');
  130. header('Cache-Control: max-age=0');
  131. $objWriter->save('php://output');
  132. exit;
  133. }
  134. /**
  135. * 设置头部信息
  136. * @param $data array
  137. * @param $fun function() 主要设置边框的粗细
  138. * @return $this
  139. */
  140. public static function setExcelHeader($data,$fun=null)
  141. {
  142. self::initialize($data,$fun);
  143. if(self::$count=count(self::$data)){
  144. if(self::$count>count(self::$cellKey)){
  145. return Json::fail('表头长度过长');
  146. }
  147. self::$cells=self::$cellKey[self::$count-1];
  148. }else{
  149. return Json::fail('data 参数二不能为空');
  150. }
  151. return new self;
  152. }
  153. /**
  154. * 设置标题
  155. * @param $title string || array ['title'=>'','name'=>'','info'=>[]]
  156. * @param $Name string
  157. * @param $info string || array;
  158. * @param $funName function($style,$A,$A2) 自定义设置头部样式
  159. * @return $this
  160. */
  161. public function setExcelTile($title='',$Name='',$info=[],$funName=null){
  162. //设置参数
  163. if(is_array($title)){
  164. if(isset($title['title'])) $title=$title['title'];
  165. if(isset($title['name'])) $Name=$title['name'];
  166. if(isset($title['info'])) $info=$title['info'];
  167. }
  168. if(empty($title))
  169. $title=self::$title;
  170. else
  171. self::$title=$title;
  172. if(empty($Name)) $Name=time();
  173. //设置Excel属性
  174. self::$PHPExcel ->getProperties()
  175. ->setCreator("Neo")
  176. ->setLastModifiedBy("Neo")
  177. ->setTitle(self::setUtf8($title))
  178. ->setSubject($Name)
  179. ->setDescription("")
  180. ->setKeywords($Name)
  181. ->setCategory("");
  182. //self::$PHPExcel ->getActiveSheet()->setCellValue('A1', $title);
  183. //文字居中
  184. // self::$PHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
  185. //self::$PHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
  186. self::$PHPExcel->setActiveSheetIndex(0);
  187. self::$PHPExcel->getActiveSheet()->setTitle($Name);
  188. //self::$PHPExcel->getActiveSheet()->setCellValue('A2',self::setCellInfo($info));
  189. //合并表头单元格
  190. //self::$PHPExcel->getActiveSheet()->mergeCells('A1:'.self::$cells.'1');
  191. //self::$PHPExcel->getActiveSheet()->mergeCells('A2:'.self::$cells.'2');
  192. self::$PHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(40);
  193. self::$PHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(20);
  194. //设置表头行高
  195. if($funName!==null && is_callable($funName)){
  196. $fontstyle=self::$PHPExcel->getActiveSheet();
  197. $funName($fontstyle,'A1','A2');
  198. }else{
  199. //设置表头字体
  200. //self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('黑体');
  201. //self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
  202. // self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
  203. // self::$PHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setName('宋体');
  204. // self::$PHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14);
  205. }
  206. self::$PHPExcel->getActiveSheet()->getStyle('A3:'.self::$cells.'3')->getFont()->setBold(true);
  207. return $this;
  208. }
  209. /**
  210. * 设置第二行标题内容
  211. * @param $info array (['name'=>'','site'=>'','phone'=>123] || ['我是表名','我是地址','我是手机号码'] ) || string 自定义
  212. * @return string
  213. */
  214. private static function setCellInfo($info){
  215. $content=['操作者:','导出日期:'.date('Y-m-d',time()),'地址:','电话:'];
  216. if(is_array($info) && !empty($info)){
  217. if(isset($info['name'])){
  218. $content[0].=$info['name'];
  219. }else{
  220. $content[0].=isset($info[0])?$info[0]:'';
  221. }
  222. if(isset($info['site'])){
  223. $content[2].=$info['site'];
  224. }else{
  225. $content[2].=isset($info[1])?$info[1]:'';
  226. }
  227. if(isset($info['phone'])){
  228. $content[3].=$info['phone'];
  229. }else{
  230. $content[3].=isset($info[2])?$info[2]:'';
  231. }
  232. return implode(' ',$content);
  233. }else if(is_string($info)){
  234. return empty($info)?implode(' ',$content):$info;
  235. }
  236. }
  237. }