【问题标题】:Export CSV using Laravel via Ajax通过 Ajax 使用 Laravel 导出 CSV
【发布时间】:2018-01-19 10:31:30
【问题描述】:

我有一个导出 csv 函数,它在 laravel 中运行良好。但是现在我想通过ajax调用导出函数并使用方法post,但我没有响应。我可以从 laravel 控制器发送一个变量来响应,但不能发送文件下载。

这是我的代码:

route.php

    Route::get('/title/show', 'TitleController@show');
    Route::post('/title/show', 'TitleController@exportFromDB');

show.blade.php

<script>
$(document).ready(function () {
    $('#exportFromDB').click(function () {
        $.ajax({
            url: "",
            type: "post",
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            data: {},
            success: function (response) {
                var a = document.createElement("a");
                a.href = response.file;
                a.download = response.name;
            }
        })
    })
})

TitleController.php:

    $dataExport['Oversea'] = $dataOversea;
    $this->titleRepository->export('csv', $properties, $dataExport);

TitleRepository.php

public function export($type, $properties, $data)
{
    if (in_array($type, self::EXPORT_TYPE)) {
        try {
            return Excel::create($properties['_title'], function ($excel) use ($data, $properties) {

                $excel->setTitle($properties['_title']);
                $excel->setCreator($properties['_creator'])
                    ->setCompany($properties['_company']);
                $excel->setDescription($properties['_description']);

                $excel->sheet('Sheet', function ($sheet) use ($data) {
                    foreach ($data as $item) {
                        $sheet->fromArray($item);
                    }
                });
            })->export($type);
        } catch (Exception $error) {
            throw $error;
        }
    }
}

我该如何修复它们?谢谢!

【问题讨论】:

    标签: php laravel laravel-5 export-to-csv maatwebsite-excel


    【解决方案1】:

    我看到你的 ajax url null 值

    改成

    url : "{{ action('TitleController@exportFromDB') }}"
    

    然后,响应是您在控制器中返回的数据

    success: function (response) {}
    

    【讨论】:

    • 我认为 null url 没有问题,因为我可以通过 return ("a") 和 die(); 将变量从控制器传递到响应; :(
    【解决方案2】:

    试试这个 -

    1. 不要在控制器方法中编写导出代码,只需将 excel 文件保存在公用文件夹中即可。

    2. 你的控制器方法应该返回文件名。

    3. 在您的 ajax 成功后执行此操作 -

    location.href = path/to/file/property_title.xls

    所以替换你的这一行

    ->export($type); 
    

    ->store($type, 'public/reports/', true);
    

    【讨论】:

    • tks 这么多,你的想法很棒,但我仍然无法返回文件名。我将 ->export() 更改为 ->store() 和 var_dump($this->titleRepository->export('csv', $properties, $dataExport)) 但它返回 null;你能告诉我如何详细重写我的控制器和存储库吗:(
    • 不是返回 Excel::create,而是将其分配给变量。像这样 $export = Excel::create 而不是 dd($export)。之后 if ($export) { return $export['full']; } 其他 { $message = empty($data) ? '没有要导出的记录' : "出了点问题请重试"; \Session::flash('error', $message);返回重定向(“客户端列表”); }
    【解决方案3】:

    我安装了 maatwebsite/excel 包,无需编写任何 javascript 即可完成。您需要做的就是设置一个链接(或典型的表单帖子,如果您愿意),如下所示:

    public downloadItemsExcel() {
        $items = Item::all();
        Excel::create('items', function($excel) use($items) {
            $excel->sheet('ExportFile', function($sheet) use($items) {
                $sheet->fromArray($items);
            });
        })->export('xls');
    }
    

    这同样适用于 csv/excel 文件。浏览器中没有重新加载页面。

    【讨论】:

      【解决方案4】:

      首先您必须将 POST 方法更改为 GET。

      对于 ajax,你可以这样做:

      $(document).ready(function () {
          $('#exportFromDB').click(function () {
            $.get('/title/show, function(data){      
              window.location = '/title/show=' + data;
            });        
          })
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-14
        • 2019-12-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多