数据导出
<p>框架提供了基础的数据导出功能, 可以很方便的实现导出数据到 <code>.xlsx</code> 文件</p>
<p>> 此功能依赖于 <a href="https://github.com/rap2hpoutre/fast-excel">fast-excel</a> ( rap2hpoutre/fast-excel )</p>
<p><br></p>
<h2>使用</h2>
<pre><code class="language-php">// 在列表工具栏添加导出按钮
public function list(): Page
{
$crud = $this-&gt;baseCRUD()
-&gt;headerToolbar([
$this-&gt;createButton(),
...$this-&gt;baseHeaderToolBar(),
// 添加导出按钮
$this-&gt;exportAction(),
])
-&gt;columns([
// ...
]);
return $this-&gt;baseList($crud);
}
</code></pre>
<p><br></p>
<h2>自定义导出信息</h2>
<h3>导出文件名</h3>
<pre><code class="language-php">// 在控制器中重写 exportFileName 方法
protected function exportFileName()
{
return '此处为导出文件名';
}</code></pre>
<p><br></p>
<h3>导出列信息</h3>
<pre><code class="language-php">// 在控制器中重写 exportMap 方法, $row 是数组格式
// 该方法会被循环调用, 请不要在里面执行 IO 操作
protected function exportMap($row)
{
return [
'姓名' =&gt; $row['name'],
'年龄' =&gt; $row['age'],
'性别' =&gt; $row['gender'],
'...'
];
}</code></pre>
<p><br></p>
<h2>完整自定义</h2>
<p>如果以上配置不能满足你的需求, 你可以重写 <code>export</code> 方法, 自定义导出逻辑</p>
<pre><code class="language-php">// 在控制器中重写 export 方法
// 此方法在 index() 中被调用, 当请求参数 _action=export 时
protected function export()
{
// 默认在 storage/app/ 下
$path = sprintf('%s-%s.xlsx', $this-&gt;exportFileName(), date('YmdHis'));
// 导出本页和导出选中项都是通过 _ids 查询
$ids = request()-&gt;input('_ids');
// listQuery() 为列表查询条件,与获取列表数据一致
$query = $this-&gt;service-&gt;listQuery()
-&gt;when($ids, fn($query) =&gt; $query-&gt;whereIn($this-&gt;service-&gt;primaryKey(), explode(',', $ids)));
try {
fastexcel($query-&gt;get())-&gt;export(storage_path('app/' . $path), fn($row) =&gt; $this-&gt;exportMap($row));
} catch (\Throwable $e) {
admin_abort(__('admin.action_failed'));
}
return $this-&gt;response()-&gt;success(compact('path'));
}</code></pre>