PHPExcelService.php 9.7 KB

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