소스 검색

优化导出功能,支持标题设置关联关系字段以及自动读取grid表格列的标题

jqh 4 년 전
부모
커밋
edc86348ab
2개의 변경된 파일47개의 추가작업 그리고 5개의 파일을 삭제
  1. 46 4
      src/Grid/Exporters/AbstractExporter.php
  2. 1 1
      src/Grid/Exporters/ExcelExporter.php

+ 46 - 4
src/Grid/Exporters/AbstractExporter.php

@@ -3,6 +3,7 @@
 namespace Dcat\Admin\Grid\Exporters;
 
 use Dcat\Admin\Grid;
+use Illuminate\Support\Arr;
 use Illuminate\Support\Str;
 
 /**
@@ -54,7 +55,9 @@ abstract class AbstractExporter implements ExporterInterface
      */
     public function __construct($titles = [])
     {
-        $this->titles($titles);
+        if ($titles) {
+            $this->titles($titles);
+        }
     }
 
     /**
@@ -62,10 +65,14 @@ abstract class AbstractExporter implements ExporterInterface
      *
      * @param array|false $titles
      *
-     * @return $this
+     * @return $this|array
      */
-    public function titles($titles)
+    public function titles($titles = null)
     {
+        if ($titles === null) {
+            return $this->titles ?: ($this->titles = $this->defaultTitles());
+        }
+
         if (is_array($titles) || $titles === false) {
             $this->titles = $titles;
         }
@@ -73,6 +80,25 @@ abstract class AbstractExporter implements ExporterInterface
         return $this;
     }
 
+    /**
+     * 读取默认标题.
+     *
+     * @return array
+     */
+    protected function defaultTitles()
+    {
+        return $this
+            ->grid
+            ->columns()
+            ->mapWithKeys(function (Grid\Column $column, $name) {
+                return [$name => $column->getLabel()];
+            })
+            ->reject(function ($v, $k) {
+                return in_array($k, ['#', Grid\Column::ACTION_COLUMN_NAME, Grid\Column::SELECT_COLUMN_NAME]);
+            })
+            ->toArray();
+    }
+
     /**
      * Set filename.
      *
@@ -190,7 +216,23 @@ abstract class AbstractExporter implements ExporterInterface
 
         $model->reset();
 
-        return $this->callBuilder($array);
+        return $this->normalize($this->callBuilder($array));
+    }
+
+    /**
+     * 格式化待导出数据.
+     *
+     * @param array $data
+     *
+     * @return array
+     */
+    protected function normalize(array $data)
+    {
+        foreach ($data as &$row) {
+            $row = Arr::dot($row);
+        }
+
+        return $data;
     }
 
     /**

+ 1 - 1
src/Grid/Exporters/ExcelExporter.php

@@ -34,7 +34,7 @@ class ExcelExporter extends AbstractExporter
             $exporter->data($this->buildData() ?: [[]]);
         }
 
-        $exporter->headings($this->titles)->download($filename);
+        $exporter->headings($this->titles())->download($filename);
 
         exit;
     }