通过 Ajax 使用 Laravel 导出 CSV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45626173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:29:20  来源:igfitidea点击:

Export CSV using Laravel via Ajax

phplaravellaravel-5export-to-csvmaatwebsite-excel

提问by Manh Nguyen

I have a export csv function, it worked fine with laravel. But now I want to call export function via ajax and use method post, but I there is no respone. I can send a variable from laravel controller to response, but can not send a file download.

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

Here is my code :

这是我的代码:

route.php

路由文件

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

show.blade.php

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:

标题控制器.php:

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

TitleRepository.php

标题库.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;
        }
    }
}

How can I fix them ? Thank !

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

回答by Mr.Gandhi

Try this -

尝试这个 -

  1. Don't write the code for export in your controller method, instead just save the excel file in your public folder.

  2. Your controller method should return the filename.

  3. On your ajax success do this -

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

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

  3. 在你的 ajax 成功时这样做 -

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

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

So replace your this line

所以更换你的这一行

->export($type); 

with

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

回答by Vu Hoang Duc

I see your ajax url null value

我看到你的 ajax url null 值

Change it to

将其更改为

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

After that, response is data you return in controller

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

success: function (response) {}

回答by omarjebari

I installed the maatwebsite/excel package and was able to do it without writing any javascript. All you need to do is setup a link (or typical form post if you prefer) to an action like so:

我安装了 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');
}

This works for csv/excel files alike. There is no reload of a page in the browser.

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

回答by Amine D

First you have to change POST method to GET.

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

For ajax you can do it like this:

对于 ajax,你可以这样做:

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