laravel 5控制器中的CSV导出

时间:2015-09-07 14:46:46

标签: php csv laravel laravel-5

所以我向reviewsController@export发了一个小的ajax请求。

现在当我console.log()成功方法中的数据时,ajax响应显示正确的数据。但是我的CSV尚未下载。所以我拥有所有正确的信息并且基本上创建了csv。

我认为这可能与设置标题有关吗?

public function export()
{
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");

    $reviews = Reviews::getReviewExport($this->hw->healthwatchID)->get();
    $columns = array('ReviewID', 'Provider', 'Title', 'Review', 'Location', 'Created', 'Anonymous', 'Escalate', 'Rating', 'Name');

    $file = fopen('php://output', 'w');
    fputcsv($file, $columns);

    foreach($reviews as $review) {
        fputcsv($file, array($review->reviewID,$review->provider,$review->title,$review->review,$review->location,$review->review_created,$review->anon,$review->escalate,$review->rating,$review->name));
    }
    exit();
}

我在这里做错了什么,或者Laravel有什么可以满足的吗?

7 个答案:

答案 0 :(得分:29)

尝试使用此版本 - 这应该可以让您使用Response::stream()获得一个不错的输出。

public function export()
{
    $headers = array(
        "Content-type" => "text/csv",
        "Content-Disposition" => "attachment; filename=file.csv",
        "Pragma" => "no-cache",
        "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
        "Expires" => "0"
    );

    $reviews = Reviews::getReviewExport($this->hw->healthwatchID)->get();
    $columns = array('ReviewID', 'Provider', 'Title', 'Review', 'Location', 'Created', 'Anonymous', 'Escalate', 'Rating', 'Name');

    $callback = function() use ($reviews, $columns)
    {
        $file = fopen('php://output', 'w');
        fputcsv($file, $columns);

        foreach($reviews as $review) {
            fputcsv($file, array($review->reviewID, $review->provider, $review->title, $review->review, $review->location, $review->review_created, $review->anon, $review->escalate, $review->rating, $review->name));
        }
        fclose($file);
    };
    return Response::stream($callback, 200, $headers);
}

(改编自此SO回答:Use Laravel to Download table as CSV

尝试使用target="_blank"的常规链接,而不是使用JavaScript / AJAX。因为它是一个新选项卡中的文件下载开放,所以用户体验不应该太笨重。

答案 1 :(得分:3)

我在Laravel 5.7中的方法

/**
 * @param array $columnNames
 * @param array $rows
 * @param string $fileName
 * @return \Symfony\Component\HttpFoundation\StreamedResponse
 */
public static function getCsv($columnNames, $rows, $fileName = 'file.csv') {
    $headers = [
        "Content-type" => "text/csv",
        "Content-Disposition" => "attachment; filename=" . $fileName,
        "Pragma" => "no-cache",
        "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
        "Expires" => "0"
    ];
    $callback = function() use ($columnNames, $rows ) {
        $file = fopen('php://output', 'w');
        fputcsv($file, $columnNames);
        foreach ($rows as $row) {
            fputcsv($file, $row);
        }
        fclose($file);
    };
    return response()->stream($callback, 200, $headers);
}

public function someOtherControllerFunction() {
    $rows = [['a','b','c'],[1,2,3]];//replace this with your own array of arrays
    $columnNames = ['blah', 'yada', 'hmm'];//replace this with your own array of string column headers        
    return self::getCsv($columnNames, $rows);
}

答案 2 :(得分:2)

这可能无法直接回答您的问题,但我正在使用名为' thephpleague/csv'为了这个目的...

要使用此包:

  1. 作曲家需要联盟/ csv
  2. 将以下内容'使用'控制器中的语句:

    use Illuminate\Database\Eloquent\Collection;
    use League\Csv\Writer;
    use Schema;
    use SplTempFileObject;
    

    以及您计划使用的任何模型类。

  3. 抽象CSV为函数(在控制器中)创建代码,例如:

    /**
     * A function to generate a CSV for a given model collection.
     *
     * @param Collection $modelCollection
     * @param $tableName
     */
    private function createCsv(Collection $modelCollection, $tableName){
    
        $csv = Writer::createFromFileObject(new SplTempFileObject());
    
        // This creates header columns in the CSV file - probably not needed in some cases.
        $csv->insertOne(Schema::getColumnListing($tableName));
    
        foreach ($modelCollection as $data){
            $csv->insertOne($data->toArray());
        }
    
        $csv->output($tableName . '.csv');
    
    }
    
  4. 在您的控制器中,创建get函数以检索/下载CSV(用您自己的模型类替换' MainMeta')

    public function getMainMetaData(){
    
        $mainMeta = MainMeta::all();
    
        // Note: $mainMeta is a Collection object 
        //(returning a 'collection' of data from using 'all()' function), 
        //so can be passed in below.
        $this->createCsv($mainMeta, 'main_meta');
    }
    

    当您创建调用此功能的路线时,它会在您的浏览器中下载所选模型集合/数据的CSV文件。

  5. 在App \ Http \ routes.php中创建一条路线,如下所示:

    Route::get(
        '/data/download/main_meta',
        [
            'as' => 'data/download/main_meta',
            'uses' => 'YourController@getMainMetaData'
        ]
    );
    
  6. (可选)在刀片视图文件(例如data.blade.php)中,包含一个链接或按钮,以便您轻松访问下载URL /路径:

    <p><a href="{{ URL::route('data/download/main_meta') }}" class="btn btn-lg btn-primary pull-left">Download Main Meta Data</a></p>
    

    点击链接后,CSV文件将在浏览器中下载。在我编码的应用程序中,您将保留在单击此链接的页面上。

  7. 当然,这取决于您自己的应用程序。您可以使用此软件包执行更多操作(完整文档位于http://csv.thephpleague.com/)。我正在使用的项目是https://github.com/rattfieldnz/bitcoin-faucet-rotator - 几个月之后我刚刚开始对它进行编码,所以仍然需要进行一些重构/测试/整理:)。

答案 3 :(得分:1)

试试这个:

<?php

public function download()
{
    $headers = [
            'Cache-Control'       => 'must-revalidate, post-check=0, pre-check=0'
        ,   'Content-type'        => 'text/csv'
        ,   'Content-Disposition' => 'attachment; filename=galleries.csv'
        ,   'Expires'             => '0'
        ,   'Pragma'              => 'public'
    ];

    $list = User::all()->toArray();

    # add headers for each column in the CSV download
    array_unshift($list, array_keys($list[0]));

   $callback = function() use ($list) 
    {
        $FH = fopen('php://output', 'w');
        foreach ($list as $row) { 
            fputcsv($FH, $row);
        }
        fclose($FH);
    };

    return Response::stream($callback, 200, $headers); //use Illuminate\Support\Facades\Response;

}

注意:只有在您不加载关系时才有效,否则会产生异常

答案 4 :(得分:0)

我已经做了一个小包装LaravelCsvGenerator

并将其放在packagist

安装

$ composer require  eugene-melbourne/laravel-csv-generator

在控制器中使用的示例

class MyController extends Controller
{

    public function getCsv(): \Symfony\Component\HttpFoundation\StreamedResponse
    {
        $data    = [
                [1, 2.1],
                [3, "hi, there"],
            ];
        $headers = ['one', 'two'];
        $data = array_merge([$headers], $data);

        return (new \LaravelCsvGenerator\LaravelCsvGenerator())
                ->setData($data)
                ->renderStream();
    }

请不要犹豫,在此答案下方评论您的想法。

答案 5 :(得分:0)

简单方法

        $headers = [
        'Cache-Control'       => 'must-revalidate, post-check=0, pre-check=0'
        ,   'Content-type'        => 'text/csv'
        ,   'Content-Disposition' => 'attachment; filename=leads.csv'
        ,   'Expires'             => '0'
        ,   'Pragma'              => 'public'
    ];
    $leads = []
    return response(view('exports.leads.csv', [ 'leads' => $leads ]))
        ->withHeaders($headers);

答案 6 :(得分:-1)

您必须将文件存储在服务器上(临时或磁盘上)并将文件的 url 发送到前端。然后通过javascript触发正常下载。

public function export(Request $request) 
{


You have to store the file on the server (either temporary or on a disk) and send the url to the file to the frontend. Then just trigger a normal download via javascript.

Thank you that's what i just did right now ?

public function export(Request $request) 
{
    $filename = Carbon::now()->format('Ymdhms').'-Products.xlsx';
    Excel::store(new ProductsExport, $filename);
    $fullPath = Storage::disk('local')->path($filename);

    return response()->json([
        'data' => $fullPath,
        'message' => 'Products are successfully exported.'
    ], 200);
}



$filename = Carbon::now()->format('Ymdhms').'-Products.xlsx';
Excel::store(new ProductsExport, $filename);
$fullPath = Storage::disk('local')->path($filename);

return response()->json([
    'data' => $fullPath,
    'message' => 'Products are successfully exported.'
], 200);
}