ViewExport.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Admin\Exports;
  3. use Encore\Admin\Grid\Exporters\AbstractExporter;
  4. use Illuminate\Contracts\View\View;
  5. use Illuminate\Support\Collection;
  6. use Illuminate\Support\Facades\Storage;
  7. abstract class ViewExport extends AbstractExporter
  8. {
  9. /**
  10. * @var Collection
  11. */
  12. private $customerData = null;
  13. /**
  14. * @return mixed
  15. */
  16. public function getCustomerData()
  17. {
  18. return $this->customerData;
  19. }
  20. /**
  21. * @param Collection $customerData
  22. * @return ViewExport
  23. */
  24. public function setCustomerData(Collection $customerData)
  25. {
  26. $this->customerData = $customerData;
  27. return $this;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function export()
  33. {
  34. $temp_path=$this->renderFile();
  35. response()->download(Storage::disk('public')
  36. ->path($temp_path), $this->getFilename())
  37. ->deleteFileAfterSend(true)
  38. ->send();
  39. exit;
  40. }
  41. public function store()
  42. {
  43. return $this->renderFile();
  44. }
  45. private function renderFile()
  46. {
  47. $view = $this->getView($this->getCustomerData()?:$this->getData(false));
  48. $temp_path="temp/".$this->getFilename();
  49. Storage::disk('public')->put($temp_path, $view->render());
  50. return $temp_path;
  51. }
  52. /**
  53. * 设置文件名
  54. * @return string
  55. */
  56. abstract public function getFilename(): string ;
  57. /**
  58. * 渲染对应的视图
  59. * @param Collection $data 导出的数据
  60. * @return View
  61. */
  62. abstract public function getView(Collection $data): View ;
  63. }