PHPExcelService.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 $data array()
  54. * @param $fun function()
  55. * return
  56. */
  57. private static function initialize(array $data, $fun)
  58. {
  59. self::$PHPExcel = new \PHPExcel();
  60. if ($fun !== null && is_callable($fun)) {
  61. self::$styleArray = $fun();
  62. }
  63. self::$data = $data;
  64. }
  65. /**
  66. *设置字体格式
  67. * @param $title string 必选
  68. * return string
  69. */
  70. public static function setUtf8($title)
  71. {
  72. return iconv('utf-8', 'gb2312', $title);
  73. }
  74. /**
  75. *
  76. * execl数据导出
  77. * @param $list 需要导出的数据 格式和以前的可是一样
  78. * @param $list 也可以为匿名函数 匿名函数参数有 $sheet PHPExcel->getActiveSheet(),self::$topNumber 从第几行设置,$cellkey 行号为数组,self::$cells现在设置的最大行号
  79. *
  80. * 特殊处理:合并单元格需要先对数据进行处理
  81. */
  82. public function setExcelContent($list = null)
  83. {
  84. $sheet = self::$PHPExcel->getActiveSheet();
  85. foreach (self::$data as $key => $val) {
  86. $row = self::$cellKey[$key];
  87. $sheet->getColumnDimension($row)->setWidth(isset($val['w']) ? $val['w'] : self::$where);
  88. $sheet->setCellValue($row . self::$topNumber, isset($val['name']) ? $val['name'] : $val);
  89. }
  90. $cellkey = array_slice(self::$cellKey, 0, self::$count);
  91. if ($list !== null && is_array($list)) {
  92. foreach ($cellkey as $k => $v) {
  93. foreach ($list as $key => $val) {
  94. if (isset($val[$k]) && !is_array($val[$k])) {
  95. $sheet->setCellValue($v . (self::$topNumber + 1 + $key), $val[$k]);
  96. } else if (isset($val[$k]) && is_array($val[$k])) {
  97. $str = '';
  98. foreach ($val[$k] as $value) {
  99. $str .= $value . chr(10);
  100. }
  101. $sheet->setCellValue($v . (self::$topNumber + 1 + $key), $str);
  102. }
  103. }
  104. }
  105. $sheet->getDefaultRowDimension()->setRowHeight(self::$height);
  106. //设置边框
  107. $sheet->getStyle('A1:' . self::$cells . (count($list) + self::$topNumber))->applyFromArray(self::$styleArray);
  108. //设置自动换行
  109. $sheet->getStyle('A4:' . self::$cells . (count($list) + self::$topNumber))->getAlignment()->setWrapText(true);
  110. } else if ($list !== null && is_callable($list)) {
  111. $list($sheet, self::$topNumber, $cellkey, self::$cells)->applyFromArray(self::$styleArray);
  112. }
  113. return $this;
  114. }
  115. /**
  116. * 保存表格数据,并下载
  117. * @param
  118. * @return
  119. */
  120. public function ExcelSave()
  121. {
  122. $objWriter = \PHPExcel_IOFactory::createWriter(self::$PHPExcel, 'Excel2007');
  123. $filename = self::$title . '--' . time() . '.xlsx';
  124. ob_end_clean();
  125. header('Content-Type: application/vnd.ms-excel');
  126. header('Content-Type: application/octet-stream');
  127. header('Content-Disposition: attachment; filename="' . $filename . '"');
  128. header('Cache-Control: max-age=0');
  129. $objWriter->save('php://output');
  130. exit;
  131. }
  132. /**
  133. * 设置头部信息
  134. * @param $data array
  135. * @param $fun function() 主要设置边框的粗细
  136. * @return $this
  137. */
  138. public static function setExcelHeader($data, $fun = null)
  139. {
  140. self::initialize($data, $fun);
  141. if (self::$count = count(self::$data)) {
  142. if (self::$count > count(self::$cellKey)) {
  143. throw new \RuntimeException('表头太长');
  144. }
  145. self::$cells = self::$cellKey[self::$count - 1];
  146. } else {
  147. throw new \RuntimeException('data 参数二不能为空');
  148. }
  149. return new self;
  150. }
  151. /**
  152. * 设置标题
  153. * @param $title string || array ['title'=>'','name'=>'','info'=>[]]
  154. * @param $Name string
  155. * @param $info string || array;
  156. * @param $funName function($style,$A,$A2) 自定义设置头部样式
  157. * @return $this
  158. */
  159. public function setExcelTile($title = '', $Name = '', $info = [], $funName = null)
  160. {
  161. //设置参数
  162. if (is_array($title)) {
  163. if (isset($title['title'])) $title = $title['title'];
  164. if (isset($title['name'])) $Name = $title['name'];
  165. if (isset($title['info'])) $info = $title['info'];
  166. }
  167. if (empty($title))
  168. $title = self::$title;
  169. else
  170. self::$title = $title;
  171. if (empty($Name)) $Name = time();
  172. //设置Excel属性
  173. self::$PHPExcel->getProperties()
  174. ->setCreator("Neo")
  175. ->setLastModifiedBy("Neo")
  176. ->setTitle(self::setUtf8($title))
  177. ->setSubject($Name)
  178. ->setDescription("")
  179. ->setKeywords($Name)
  180. ->setCategory("");
  181. self::$PHPExcel->getActiveSheet()->setCellValue('A1', $title);
  182. //文字居中
  183. self::$PHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
  184. self::$PHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
  185. self::$PHPExcel->setActiveSheetIndex(0);
  186. self::$PHPExcel->getActiveSheet()->setTitle($Name);
  187. self::$PHPExcel->getActiveSheet()->setCellValue('A2', self::setCellInfo($info));
  188. //合并表头单元格
  189. self::$PHPExcel->getActiveSheet()->mergeCells('A1:' . self::$cells . '1');
  190. self::$PHPExcel->getActiveSheet()->mergeCells('A2:' . self::$cells . '2');
  191. self::$PHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(40);
  192. self::$PHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(20);
  193. //设置表头行高
  194. if ($funName !== null && is_callable($funName)) {
  195. $fontstyle = self::$PHPExcel->getActiveSheet();
  196. $funName($fontstyle, 'A1', 'A2');
  197. } else {
  198. //设置表头字体
  199. self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('黑体');
  200. self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
  201. self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
  202. self::$PHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setName('宋体');
  203. self::$PHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14);
  204. }
  205. self::$PHPExcel->getActiveSheet()->getStyle('A3:' . self::$cells . '3')->getFont()->setBold(true);
  206. return $this;
  207. }
  208. /**
  209. * 设置第二行标题内容
  210. * @param $info array (['name'=>'','site'=>'','phone'=>123] || ['我是表名','我是地址','我是手机号码'] ) || string 自定义
  211. * @return string
  212. */
  213. private static function setCellInfo($info)
  214. {
  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. }