当前位置:   article > 正文

ThinkPHP6 自定义Excel导出

ThinkPHP6 自定义Excel导出

一、说明

1.需要安装Spreadsheet,如未安装自行composer安装即可

2.定义导出表格的表头(及键值)

3.数据内容需要与定义的表头一致

二、核心代码

  1. try {
  2. // 获取表格数据
  3. $list = (new Activity())->select()->toArray();
  4. if (!empty($list)) {
  5. // 设置key
  6. $key = [
  7. ['key' => 'index', 'title' => '序号'],
  8. ['key' => 'activity_name', 'title' => '名称'],
  9. ['key' => 'student_name', 'title' => '学生姓名'],
  10. ];
  11. $sheet = new Spreadsheet();
  12. $activeSheet = new ExcelLogic($sheet);
  13. // 计算总列数
  14. $allColumn = count($key);
  15. // 计算总行数
  16. $allRow = count($list);
  17. // 重制表格数据,与键值对应
  18. $newArr = [];
  19. foreach ($list as $k => $v) {
  20. $newArr[$k]['index'] = $k + 1;
  21. $newArr[$k]['activity_name'] = $v['activity']['title'];
  22. $newArr[$k]['student_name'] = $v['student']['name'];
  23. }
  24. // 添加表内容
  25. for ($i = 0; $i < $allColumn; $i++) {
  26. // 设置标题
  27. $activeSheet->setCellsValue(1, $i + 1, $key[$i]['title'])
  28. ->setAlign(1, $i + 1)
  29. ->setrgBgColor(1, $i + 1, 1, '7f89e6')
  30. ->setFont(1, $i + 1, 1, 'ffffff')
  31. ->setBorder(1, $i + 1)
  32. ->setRowAndCol(1, $i + 1, 24, strlen($key[$i]['title']));
  33. // 设置内容
  34. for ($j = 0; $j < $allRow; $j++) {
  35. $rowData = $newArr[$j][$key[$i]['key']];
  36. $activeSheet->setCellsValue($j + 2, $i + 1, strval($rowData))
  37. ->setAlign($j + 2, $i + 1)
  38. ->setBorder($j + 2, $i + 1);
  39. }
  40. }
  41. // 导出表格
  42. $writer = IOFactory::createWriter($sheet, 'Xlsx');
  43. //创建excel文件
  44. $exportCache = new ExportCache();
  45. $src = $exportCache->getSrc();
  46. if (!file_exists($src)) {
  47. mkdir($src, 0775, true);
  48. }
  49. $filename = '报名列表数据导出_' . date('YmdH') . '.xlsx';
  50. $writer->save($src . $filename);
  51. // 返回下载地址
  52. }
  53. return $this->success('', ['url' => ''], 2);
  54. } catch (\Exception $e) {
  55. return $this->fail($e->getMessage());
  56. }

三、ExcelLogic类

  1. <?php
  2. namespace app\common\logic;
  3. use PhpOffice\PhpSpreadsheet\Style\Color;
  4. use PhpOffice\PhpSpreadsheet\Style\Fill;
  5. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  6. /**
  7. * @note Excel处理
  8. */
  9. class ExcelLogic
  10. {
  11. // 定义sheet
  12. private object $sheet;
  13. // 定义当前操作工作表
  14. private object $currentSheet;
  15. /**
  16. * @note 初始化
  17. * @param object $sheet
  18. * @param int $sheetIndex
  19. */
  20. public function __construct(object $sheet, int $sheetIndex = 0)
  21. {
  22. $this->sheet = $sheet;
  23. // $this->sheet = new Spreadsheet();
  24. $this->currentSheet = $this->sheet->getActiveSheet($sheetIndex);
  25. }
  26. /**
  27. * @notes 设置工作表名
  28. * @param string $title 表名
  29. * @return ExcelLogic
  30. */
  31. public function setTitle(string $title = '模板'): ExcelLogic
  32. {
  33. $this->currentSheet->setTitle($title);
  34. return $this;
  35. }
  36. /**
  37. * @notes 设置字体样式
  38. * @param int $row 行
  39. * @param int $col 列
  40. * @param string $fontName 字体名称
  41. * @param string $fontSize 字体大小
  42. * @param bool $isBold 是否加粗
  43. * @param string $fontColor 字体颜色
  44. * @param bool $isWrap 是否自动换行
  45. * @param int $colSpan 列跨度
  46. * @return ExcelLogic
  47. */
  48. public function setFont(
  49. int $row = 1,
  50. int $col = 1,
  51. int $colSpan = 1,
  52. string $fontColor = '000000',
  53. bool $isBold = false,
  54. string $fontName = '宋体',
  55. string $fontSize = '14',
  56. bool $isWrap = true,
  57. ): ExcelLogic
  58. {
  59. $this->currentSheet->getStyleByColumnAndRow($col, $row, $col + $colSpan - 1, $row)->getFont()
  60. ->setName($fontName)
  61. ->setSize($fontSize)
  62. ->setBold($isBold)
  63. ->setColor(new Color($fontColor));
  64. // 自动换行
  65. $this->currentSheet->getStyleByColumnAndRow($col, $row, $col + $colSpan - 1, $row)->getAlignment()->setWrapText($isWrap);
  66. return $this;
  67. }
  68. /**
  69. * @notes 设置文字对齐方式
  70. * @param int $row 行
  71. * @param int $col 列
  72. * @param string $alignHorizontal 水平对齐方式
  73. * @param string $alignVertical 垂直对齐方式
  74. * @return ExcelLogic
  75. */
  76. public function setAlign(int $row = 1, int $col = 1, string $alignHorizontal = 'center', string $alignVertical = 'center'): ExcelLogic
  77. {
  78. // 水平居中
  79. $this->currentSheet->getStyleByColumnAndRow($col, $row)->getAlignment()->setHorizontal($alignHorizontal);
  80. // 垂直居中
  81. $this->currentSheet->getStyleByColumnAndRow($col, $row)->getAlignment()->setVertical($alignVertical);
  82. return $this;
  83. }
  84. /**
  85. * @notes 行高及列宽
  86. * @param int $row 行
  87. * @param int $col 列
  88. * @param int $rowHeight 行高
  89. * @param int $colWidth 列宽
  90. * @return ExcelLogic
  91. */
  92. public function setRowAndCol(int $row = 1, int $col = 1, int $rowHeight = 24, int $colWidth = 20): ExcelLogic
  93. {
  94. // 设置行高
  95. $this->currentSheet->getRowDimension($row)->setRowHeight($rowHeight);
  96. $this->currentSheet->getColumnDimensionByColumn($col)->setWidth($colWidth);
  97. return $this;
  98. }
  99. /**
  100. * @notes 设置边框
  101. * @param int $row 开始行
  102. * @param int $col 开始列
  103. * @param int $colSpan 列合并数
  104. * @param string $borderStyle 边框样式
  105. * @param string $borderColor 边框颜色
  106. * @return ExcelLogic
  107. */
  108. public function setBorder(
  109. int $row = 1,
  110. int $col = 1,
  111. int $colSpan = 1,
  112. string $borderStyle = 'thin',
  113. string $borderColor = '000000'
  114. ): ExcelLogic
  115. {
  116. // 设置边框样式
  117. $this->currentSheet->getStyleByColumnAndRow($col, $row, $col + $colSpan - 1, $row)->getBorders()
  118. ->getallBorders()
  119. ->setBorderStyle($borderStyle)->setColor(new Color($borderColor));
  120. return $this;
  121. }
  122. /**
  123. * @notes 设置背景色
  124. * @param int $row 开始行
  125. * @param int $col 开始列
  126. * @param int $colSpan 列合并数
  127. * @param string $bgColor 背景色
  128. * @return ExcelLogic
  129. */
  130. public function setrgBgColor(int $row = 1, int $col = 1, int $colSpan = 1, string $bgColor = 'ffffff'): ExcelLogic
  131. {
  132. // 设置背景色
  133. $this->currentSheet->getStyleByColumnAndRow($col, $row, $col + $colSpan - 1, $row)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB($bgColor);
  134. return $this;
  135. }
  136. /**
  137. * @notes 设置单元格内容
  138. * @param int $row 行
  139. * @param int $col 列
  140. * @param string $title 表头名称
  141. * @param int $dataRow 内容
  142. * @param string|int $data 内容
  143. * @return ExcelLogic
  144. */
  145. public function setCellValue(
  146. int $row = 1,
  147. int $col = 1,
  148. string $title = '序号',
  149. string|int $data = '',
  150. int $dataRow = 0,
  151. ): ExcelLogic
  152. {
  153. // 设置表头
  154. $this->currentSheet->setCellValueByColumnAndRow($col, $row, $title);
  155. // 设置内容
  156. if ($dataRow == 0) $dataRow = $row + 1;
  157. $this->currentSheet->setCellValueByColumnAndRow($col, $dataRow, $data);
  158. return $this;
  159. }
  160. /**
  161. * @notes 设置单元格内容
  162. * @param int $row 行
  163. * @param int $col 列
  164. * @param string $data 内容
  165. * @return ExcelLogic
  166. */
  167. public function setCellsValue(
  168. int $row = 1,
  169. int $col = 1,
  170. string $data = '',
  171. ): ExcelLogic
  172. {
  173. // 设置内容
  174. $this->currentSheet->setCellValueByColumnAndRow($col, $row, $data);
  175. return $this;
  176. }
  177. /**
  178. * @notes 合并列并设置内容
  179. * @param string $val 单元格内容
  180. * @param int $col 开始列
  181. * @param int $colSpan 列合并数
  182. * @param int $row 合并行
  183. * @param string $bgColor 背景色
  184. * @param string $align 文字对齐
  185. * @param string $fontColor 字体颜色
  186. * @param string $fontSize 字体大小
  187. * @param bool $isBold 字体粗细
  188. * @param string $fontName 字体名称
  189. * @param bool $isWrap 是否自动换行
  190. * @param float $rowHeight 行高
  191. * @return ExcelLogic
  192. */
  193. public
  194. function mergeCell(
  195. string $val,
  196. int $col = 1,
  197. int $colSpan = 1,
  198. int $row = 1,
  199. string $bgColor = 'FFFFFF',
  200. string $align = 'left',
  201. string $fontColor = 'ff4040',
  202. string $fontSize = '14',
  203. bool $isBold = true,
  204. string $fontName = '宋体',
  205. bool $isWrap = true,
  206. float $rowHeight = 60
  207. ): ExcelLogic
  208. {
  209. $this->currentSheet->mergeCellsByColumnAndRow($col, $row, $col + $colSpan - 1, $row);
  210. $this->currentSheet->setCellValueByColumnAndRow($col, $row, $val);
  211. $this->setFont($row, $col, $colSpan, $fontColor, $isBold, $fontName, $fontSize, $isWrap);
  212. $this->setAlign($row, $col, $align);
  213. $this->setRowAndCol($row, $col, $rowHeight);
  214. $this->setBorder($row, $col, $colSpan);
  215. $this->setrgBgColor($row, $col, $colSpan, $bgColor);
  216. return $this;
  217. }
  218. /**
  219. * @notes 新建工作表
  220. * @param string $title 工作表名称
  221. * @param int $sheetIndex 工作表序号
  222. * @param array $tableArr 表头数组
  223. * @param array $keys 键值数组
  224. * @param array $dataArr 数据数组
  225. * @return ExcelLogic
  226. */
  227. public function createSheet(string $title = 'sheet1', int $sheetIndex = 1, array $tableArr = [], array $keys = [], array $dataArr = []): ExcelLogic
  228. {
  229. // 新建工作表
  230. $newSheet = new Worksheet($this->sheet, $title);
  231. $this->sheet->addSheet($newSheet, $sheetIndex);
  232. // 计算总列数
  233. $totalCol = count($tableArr);
  234. $colArr = $this->getColumn($totalCol);
  235. // 添加数据内容
  236. for ($i = 0; $i < $totalCol; $i++) {
  237. // 设置表头
  238. $newSheet->setCellValue($colArr[$i] . 1, $tableArr[$i]);
  239. for ($j = 0; $j < count($dataArr); $j++) {
  240. // 设置内容
  241. $newSheet->setCellValue($colArr[$i] . $j + 2, $dataArr[$j][$keys[$i]]);
  242. }
  243. }
  244. return $this;
  245. }
  246. /**
  247. * @notes 自动计算列数
  248. * @param string $col
  249. */
  250. public
  251. function getColumn(int $colNumber = 1)
  252. {
  253. // 生成A-Z的数组
  254. $arr = range('A', 'Z');
  255. // 计算循环次数
  256. $no = ceil($colNumber / count($arr));
  257. // 定义数组
  258. $data = [];
  259. if ($no <= 1) {
  260. for ($i = 0; $i < $colNumber; $i++) {
  261. $data[] = $arr[$i];
  262. }
  263. } else {
  264. for ($i = 0; $i < count($arr); $i++) {
  265. $data[] = $arr[$i];
  266. }
  267. for ($i = 0; $i < $colNumber - count($arr); $i++) {
  268. $list = (($i + count($arr)) % count($arr));
  269. $data[] = $arr[ceil(($i + 1) / count($arr)) - 1] . $arr[$list];
  270. }
  271. }
  272. return $data;
  273. }
  274. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/40405
推荐阅读
相关标签
  

闽ICP备14008679号