ExportTrait.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Console\Commands\Export;
  3. use Carbon\Carbon;
  4. use function EasyWeChat\Kernel\Support\str_random;
  5. trait ExportTrait
  6. {
  7. public $filename;
  8. public $path;
  9. public $fd;
  10. public function createdFile($directory, $name){
  11. //$this->filename = Carbon::today()->toDateString().'-'.str_random('5').'-'.$name.'.xlsx';
  12. $this->filename = $name.'.xlsx';
  13. //$this->path = storage_path('exports/' . $this->filename);
  14. $this->path = $directory . '/' . $this->filename;// storage_path('exports/' . $this->filename);
  15. //$this->path = $path;
  16. $dirPath = dirname($this->path);
  17. // 确保目录存在
  18. // if (!is_dir($dirPath)) {
  19. // mkdir($dirPath, 0777, true);
  20. // }
  21. if (is_dir($dirPath)) {
  22. $this->fd = fopen($this->path, 'w+');
  23. if ($this->fd) {
  24. //add BOM to fix UTF-8 in Excel
  25. fputs($this->fd, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF)));
  26. /* $table = $data;
  27. foreach ($table as $fields) {
  28. fputcsv($fd, $fields);
  29. }*/
  30. //fclose($fd);
  31. }
  32. }
  33. }
  34. public function putRow($row)
  35. {
  36. if (!$this->fd) {
  37. $this->fd = fopen($this->path, 'a+');
  38. }
  39. return fputcsv($this->fd, $row);
  40. }
  41. public function closeFile()
  42. {
  43. if ($this->fd) {
  44. fclose($this->fd);
  45. $this->fd = null;
  46. }
  47. }
  48. }