网上的解决方案几乎是使用改源码, 但是一旦项目进行composer update那修改的东西就没了
我参考了哈皮人的全栈技术博客写了一套通过继承的解决方案
- 在
app/Admin/Extentsions中添加一个自定义导出类
<?php
namespace App\Admin\Extensions;
use Encore\Admin\Grid\Column;
use Encore\Admin\Grid\Exporters\CsvExporter;
class MyCsvExporter extends CsvExporter
{
// 这个方法照搬自CsvExporter的export方法
public function export()
{
if ($this->callback) {
call_user_func($this->callback, $this);
}
$response = function () {
$handle = fopen('php://output', 'w');
$titles = [];
// 方法中所有的内容都没改, 只有添加了下面一行的代码
fputs($handle, chr(0xEF).chr(0xBB).chr(0xBF), 3);
$this->chunk(function ($collection) use ($handle, &$titles) {
Column::setOriginalGridModels($collection);
$original = $current = $collection->toArray();
$this->grid->getColumns()->map(function (Column $column) use (&$current) {
$current = $column->fill($current);
$this->grid->columnNames[] = $column->getName();
});
// Write title
if (empty($titles)) {
fputcsv($handle, $titles = $this->getVisiableTitles());
}
// Write rows
foreach ($current as $index => $record) {
fputcsv($handle, $this->getVisiableFields($record, $original[$index]));
}
});
fclose($handle);
};
response()->stream($response, 200, $this->getHeaders())->send();
exit;
}
}
- 在
app/Admin/bootstrap.php中添加以下代码
use Encore\Admin\Grid\Exporter;
use App\Admin\Extensions\MyCsvExporter;
Exporter::extend('export', MyCsvExporter::class);
// export为我设置的别名, 你们可以任意改成其他的
3.在需要的地方使用
$grid->exporter('export');