Excel.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. <?php
  2. namespace App\libs\helpers;
  3. use PhpOffice\PhpSpreadsheet\IOFactory;
  4. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  5. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  6. use PhpOffice\PhpSpreadsheet\Style\Border;
  7. use PhpOffice\PhpSpreadsheet\Style\Fill;
  8. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  9. use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
  10. class Excel
  11. {
  12. /**
  13. * 初始实例化.
  14. *
  15. * @var Spreadsheet|null
  16. */
  17. private $excel;
  18. /**
  19. * 导出暂存地址
  20. *
  21. * @var string
  22. */
  23. private $path = '';
  24. /**
  25. * 定义表格格子 最高到AG.
  26. *
  27. * @var string[]
  28. */
  29. private $ziMu = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG'];
  30. /**
  31. * 标题.
  32. *
  33. * @var array
  34. */
  35. private $title = [];
  36. /**
  37. * 导入数据源.
  38. *
  39. * @var array
  40. */
  41. private $data = [];
  42. /**
  43. * 默认域名.
  44. *
  45. * @var string
  46. */
  47. private $defaultDomain = '';
  48. /**
  49. * 是否自动换行.
  50. *
  51. * @var bool
  52. */
  53. private $setWrapText = true;
  54. /**
  55. * 导出表格名称.
  56. *
  57. * @var string
  58. */
  59. private $excelName = '';
  60. /**
  61. * 保存导出图片的配置.
  62. *
  63. * @var null
  64. */
  65. private $images;
  66. /**
  67. * 实例化.
  68. *
  69. * @var Spreadsheet|null
  70. */
  71. private $spreadsheet;
  72. /**
  73. * 是否输出导出地址
  74. *
  75. * @var bool
  76. */
  77. private $isExportPath = false;
  78. /**
  79. * 导出的地址
  80. *
  81. * @var string
  82. */
  83. public $exportPath = '';
  84. /**
  85. * 项目编号.
  86. *
  87. * @var string
  88. */
  89. private $projectName = '';
  90. /**
  91. * 项目导出文件暂存地址
  92. *
  93. * @var string
  94. */
  95. private $projectExcelPath = '';
  96. /**
  97. * 格式是否为图片.
  98. *
  99. * @var array
  100. */
  101. private $ceilImage = [];
  102. /**
  103. * 格式图片样式.
  104. *
  105. * @var array
  106. */
  107. private $ceilImageStyle = [];
  108. /**
  109. * 设置行高.
  110. *
  111. * @var int
  112. */
  113. public $height = -1;
  114. /**
  115. * 初始化.
  116. */
  117. public function __construct(array $data = [], array $title = [], string $path = 'uploads')
  118. {
  119. $this->spreadsheet = new Spreadsheet();
  120. $this->excel = $this->spreadsheet->getActiveSheet();
  121. $this->projectName = $this->getProjectName();
  122. $this->path = $_SERVER['DOCUMENT_ROOT'] . '/' . $this->getProjectExcelPath() . '/' . $path;
  123. $this->projectExcelPath = $path;
  124. $this->data = $data;
  125. $this->title = $title;
  126. $this->getUrl();
  127. if ($this->checkWindows()) {
  128. if (!is_dir($this->path)) {
  129. mkdir($this->path, 0777, true);
  130. chmod($this->path, 0777);
  131. }
  132. }
  133. }
  134. /**
  135. * 获取项目多字段地址
  136. */
  137. private function getProjectExcelPath(): string
  138. {
  139. $url = $_SERVER['REQUEST_URI'];
  140. $parts = explode('/', $url);
  141. $keys = array_keys($parts);
  142. $key = array_filter($parts, function ($value) {
  143. return false !== strpos($value, 'index.php');
  144. });
  145. $keySa = array_keys($key);
  146. $key = count($keys) - ($keySa[0] - 1);
  147. return implode('/', array_slice($parts, 1, $keys[count($keys) - $key]));
  148. }
  149. /**
  150. * 设置自动行高.
  151. *
  152. * @return void
  153. */
  154. private function setAutoHeight()
  155. {
  156. for ($i = 0; $i < count($this->data); $i++) {
  157. $this->excel->getRowDimension($i + 2)->setRowHeight($this->height);
  158. }
  159. }
  160. /**
  161. * 获取域名地址
  162. *
  163. * @return void
  164. */
  165. private function getUrl()
  166. {
  167. $host = $_SERVER['HTTP_HOST'];
  168. $scriptName = $_SERVER['SCRIPT_NAME'];
  169. $this->defaultDomain = isset($_SERVER['HTTPS']) && 'on' === $_SERVER['HTTPS'] ? 'https://' : 'http://' . $host . substr($scriptName, 0, strrpos($scriptName, '/') + 1);
  170. }
  171. /**
  172. * 设置自动行宽.
  173. *
  174. * @return void
  175. */
  176. private function setAutoWidth()
  177. {
  178. foreach ($this->title ?? [] as $key => $value) {
  179. $this->excel->getColumnDimension($this->ziMu[$key])->setAutoSize(true); // 全局自动宽度
  180. $columnDimension = $this->excel->getColumnDimension($this->ziMu[$key]);
  181. $maxWidth = 50; // 自定义最大宽度
  182. if ($columnDimension->getWidth() > $maxWidth) {
  183. $columnDimension->setWidth($maxWidth);
  184. }
  185. }
  186. }
  187. /**
  188. * 获取项目名称.
  189. *
  190. * @return false|string
  191. */
  192. private function getProjectName()
  193. {
  194. $route = $_SERVER['REQUEST_URI'];
  195. $pattern = '/\/(\w+)\/index\.php/';
  196. preg_match($pattern, $route, $matches);
  197. if (isset($matches[1])) {
  198. return $matches[1];
  199. }
  200. return false;
  201. }
  202. /**
  203. * 验证是否Windows系统
  204. */
  205. private function checkWindows(): bool
  206. {
  207. $os = PHP_OS;
  208. if ('WIN' === strtoupper(substr($os, 0, 3))) {
  209. return true;
  210. }
  211. return false;
  212. }
  213. /**
  214. * 设置表格名称.
  215. *
  216. * @return $this
  217. */
  218. public function setExcelName(string $excelName = ''): Excel
  219. {
  220. $this->excelName = $excelName;
  221. return $this;
  222. }
  223. /**
  224. * 设置格子颜色.
  225. *
  226. * @param int $height //表头高度
  227. * @param string $color //表头颜色
  228. * @param bool $isBold //表头是否加粗
  229. *
  230. * @return $this
  231. *
  232. * @throws \think\Exception
  233. */
  234. public function setHeaderColor(int $height = 20, string $color = 'FFFF00', bool $isBold = true): Excel
  235. {
  236. $this->excel->getStyle($this->getRange(1))->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB($color);
  237. $this->excel->getStyle($this->getRange(1))->getFont()->setBold($isBold);
  238. $this->excel->getRowDimension(1)->setRowHeight($height);
  239. return $this;
  240. }
  241. /**
  242. * 设置是否导出地址
  243. */
  244. public function setIsExportPath(bool $isExportPath): Excel
  245. {
  246. $this->isExportPath = $isExportPath;
  247. return $this;
  248. }
  249. /**
  250. * 设置是否开启本地.
  251. *
  252. * @param string $localhostPath 本地域名地址 如果域名下一级目录不能直接直接对应项目名称 请传入域名下的相对路径
  253. */
  254. public function setLocalhostPath(string $localhostPath): Excel
  255. {
  256. $this->defaultDomain = $localhostPath;
  257. return $this;
  258. }
  259. /**
  260. * 设置边框.
  261. *
  262. * @throws \PhpOffice\PhpSpreadsheet\Exception
  263. */
  264. public function borderThin(): Excel
  265. {
  266. $this->excel->getStyle($this->getRange())->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
  267. return $this;
  268. }
  269. /**
  270. * 设置自动换行.
  271. *
  272. * @return $this
  273. */
  274. public function setAutoWrapText(bool $wrap = true): Excel
  275. {
  276. $this->setWrapText = $wrap;
  277. return $this;
  278. }
  279. /**
  280. * 设置全局居中.
  281. *
  282. * @return void
  283. *
  284. * @throws \think\Exception
  285. */
  286. private function setCenter()
  287. {
  288. $this->excel->getStyle($this->getRange())->applyFromArray([
  289. 'alignment' => [
  290. 'horizontal' => Alignment::HORIZONTAL_CENTER, // 水平居中
  291. 'vertical' => Alignment::VERTICAL_CENTER, // 垂直居中
  292. ],
  293. ]);
  294. }
  295. /**
  296. * 保存并导出.
  297. *
  298. * @return $this
  299. */
  300. public function save(): Excel
  301. {
  302. $this->setCenter();
  303. $this->setWrap();
  304. $this->setCellValue();
  305. $this->setAutoWidth();
  306. $this->setAutoHeight();
  307. $this->exportData();
  308. $writer = new Xlsx($this->spreadsheet);
  309. if (empty($this->excelName)) {
  310. $this->excelName = date('YmdHis');
  311. }
  312. $writer->save($this->path . '/' . $this->excelName . '.xlsx');
  313. if ($this->isExportPath) {
  314. $this->exportPath = $this->defaultDomain . '/' . $this->projectExcelPath . '/' . $this->excelName . '.xlsx';
  315. } else {
  316. header('Location: ' . $this->defaultDomain . '/' . $this->projectExcelPath . '/' . $this->excelName . '.xlsx');
  317. }
  318. return $this;
  319. }
  320. /**
  321. * 创建图片.
  322. *
  323. * @throws \PhpOffice\PhpSpreadsheet\Exception
  324. */
  325. private function setImage(string $url = '', string $ceil = '')
  326. {
  327. $src = imagecreatefromstring(file_get_contents($url));
  328. list($src_w, $src_h) = getimagesize($url);
  329. $img = imagecreatetruecolor($src_w, $src_h);
  330. imagecopymerge($img, $src, 0, 0, 0, 0, $src_w, $src_h, 100);
  331. $drawing = new MemoryDrawing();
  332. $drawing->setName($url);
  333. $drawing->setDescription($url);
  334. $drawing->setCoordinates($ceil);
  335. $drawing->setImageResource($img);
  336. $drawing->setHeight(80);
  337. $drawing->setOffsetX(10);
  338. $drawing->setOffsetY(10);
  339. $drawing->setRenderingFunction(MemoryDrawing::RENDERING_JPEG);
  340. $drawing->setMimeType(MemoryDrawing::MIMETYPE_DEFAULT);
  341. if (!empty($this->ceilImageStyle)) {
  342. $ceilText = substr($ceil, 0, 1);
  343. if (!empty($this->ceilImageStyle[$ceilText])) {
  344. $drawing->setHeight($this->ceilImageStyle[$ceilText]['height']);
  345. $drawing->setWidth($this->ceilImageStyle[$ceilText]['width']);
  346. $drawing->setOffsetX($this->ceilImageStyle[$ceilText]['OffsetX']);
  347. $drawing->setOffsetY($this->ceilImageStyle[$ceilText]['OffsetY']);
  348. }
  349. }
  350. $drawing->setWorksheet($this->spreadsheet->getActiveSheet());
  351. }
  352. /**
  353. * 设置格子是否导出为图片.
  354. *
  355. * @return $this
  356. */
  357. public function setExportCeilImage(array $images = []): Excel
  358. {
  359. $this->images = $images;
  360. if (count($images) != count($images, 1)) {
  361. foreach ($images ?? [] as $v) {
  362. $this->ceilImage[] = key($images);
  363. next($images);
  364. }
  365. $this->ceilImageStyle = $images;
  366. } else {
  367. $this->ceilImage = $images;
  368. }
  369. return $this;
  370. }
  371. /**
  372. * 设置导出数据.
  373. */
  374. private function exportData()
  375. {
  376. $index = 2;
  377. $keyName = $this->getArrayKey();
  378. for ($i = 0; $i < count($this->data); $i++) {
  379. for ($j = 0; $j < count($this->title); $j++) {
  380. if (in_array($this->ziMu[$j], $this->ceilImage)) {
  381. if (!empty($this->data[$i][$keyName[$j]])) {
  382. $this->excel->getColumnDimension($this->ziMu[$j])->setWidth($this->images[$this->ziMu[$j]]['width']); // 设置图片宽度
  383. $this->excel->getRowDimension($i + 2)->setRowHeight($this->images[$this->ziMu[$j]]['height']);
  384. $this->setImage($this->data[$i][$keyName[$j]], $this->ziMu[$j] . $index);
  385. }
  386. } else {
  387. $this->excel->setCellValue($this->ziMu[$j] . $index, $this->data[$i][$keyName[$j]]);
  388. }
  389. }
  390. $index++;
  391. }
  392. }
  393. /**
  394. * 获取数组指针.
  395. */
  396. private function getArrayKey(): array
  397. {
  398. $result = [];
  399. if (empty($this->data)) {
  400. throw new \think\Exception('传入表数据为空', 40004);
  401. }
  402. for ($i = 0, $len = count($this->data[0]); $i < $len; $i++) {
  403. $result[] = key($this->data[0]);
  404. next($this->data[0]);
  405. }
  406. return $result;
  407. }
  408. /**
  409. * 设置自动换行.
  410. */
  411. private function setWrap()
  412. {
  413. if ($this->setWrapText) {
  414. $this->excel->getStyle($this->getRange())->getAlignment()->setWrapText(true);
  415. }
  416. }
  417. /**
  418. * 获取数据范围值
  419. *
  420. * @return string
  421. *
  422. * @throws \think\Exception
  423. */
  424. private function getRange($type = 0)
  425. {
  426. if (empty($this->title) || empty($this->data)) {
  427. throw new \think\Exception('初始化请传入数据', 40006);
  428. }
  429. if (0 == $type) {
  430. return 'A1:' . $this->ziMu[count($this->title) - 1] . (count($this->data) + 1);
  431. }
  432. return 'A1:' . $this->ziMu[count($this->title) - 1] . '1';
  433. }
  434. /**
  435. * 设置表头.
  436. *
  437. * @return void
  438. *
  439. * @throws \think\Exception
  440. */
  441. private function setCellValue()
  442. {
  443. if (empty($this->title)) {
  444. throw new \think\Exception('传入表头为空', 40005);
  445. }
  446. foreach ($this->title as $key => $value) {
  447. $this->excel->setCellValue($this->ziMu[$key] . '1', $this->title[$key]);
  448. }
  449. }
  450. /**
  451. * 获取Xlsx表格数据.
  452. *
  453. * @return array|false
  454. *
  455. * @throws \PhpOffice\PhpSpreadsheet\Exception
  456. * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
  457. */
  458. public static function getXlsxData($file, array $cell = [])
  459. {
  460. if (!$file) {
  461. return false;
  462. }
  463. $reader = IOFactory::createReader('Xlsx');
  464. $reader->setReadDataOnly(true);
  465. $spreadsheet = $reader->load($file);
  466. $worksheet = $spreadsheet->getActiveSheet();
  467. $arr = [];
  468. $i = 0;
  469. $field = $cell;
  470. $max = count($field);
  471. foreach ($worksheet->getRowIterator() as $row) {
  472. $k = 0;
  473. $cellIterator = $row->getCellIterator();
  474. $cellIterator->setIterateOnlyExistingCells(false);
  475. foreach ($cellIterator as $cell) {
  476. if ($k == $max) {
  477. break;
  478. }
  479. $arr[$i][$field[$k]] = $cell->getCalculatedValue();
  480. $k++;
  481. }
  482. $i++;
  483. }
  484. return $arr;
  485. }
  486. }