通过 Maatwebsite 导出 CSV,Laravel

Export CSV via Maatwebsite , Laravel

我尝试导出一个包含一些数据的 csv 文件,但使用我当前的代码我得到响应 200 和一些奇怪的字符,并且没有下载,不知道为什么。

来源URLhere.

Exports/DataExport.php

namespace App\Exports;
use App\ViewData;
use Maatwebsite\Excel\Concerns\FromCollection;
use Excel;

class DataExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return ViewData::all();
    }
}

控制器

use App\ViewData;
use App\Exports\DataExport;

use Maatwebsite\Excel\Facades\Excel;
    .....
    //  Export CSV data
    public function export() 
    {
        return Excel::download(new DataExport, 'data.xlsx');
    }

我在 config/app.php 文件中添加了服务提供商和别名。

您正在从前端框架下载 csv 文件,所以它当然会给您一些奇怪的字符而不是下载整个文件,让我给您一个简短的代码

downloadCSV() {
let newWindow = window.open();
axios.get('/json/persons/export')
   .then(response => {
     newWindow.location = 'http://' + window.location.hostname + '/json/persons/export';
   });
}

您需要手动点击 url 才能进行下载。剩下的我想你就明白了。