PHPExcelService.php 9.8 KB

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