为表结果创建csv下载

时间:2014-11-06 16:17:20

标签: php laravel laravel-4

我需要为表格结果视图创建一个带有下载按钮的csv文件。我正在使用Laravel框架,我不确定如何做到这一点。

我的控制器获取数据。

    public function reportFailedPayments(){
    $startdate = Input::get('startdate');
    $enddate = Input::get('enddate');
    $status = Input::get('status');
    $data = Payment::with('purchase', 'history', 'history.billingInformation', 'purchase.user', 'purchase.productInstance', 'purchase.productInstance.product', 'billingInformation')
            ->where('Status', '=',$status)->whereBetween('Payment_Date', array($startdate, $enddate))->orderBy('Payment_Date','desc')->get();
    return View::make('admin.reports.failedPayments.report', array('payments'=>$data));
}

}

这是我的表格视图。只是需要一些关于如何为csv创建DL的建议。

<table class='list'>
<thead>
<tr>
<th>Customer Name</th>
<th>Customer Email</th>
<th>Product Name</th>
<th>Purchase Date</th>
<th>Initial Payment Date</th>
<th>Last Payment Date</th>
<th>Billing Method</th>
<th>Transaction Code</th>
<th>Transaction Message</th>
</tr>
</thead>
<tbody>
@foreach($payments as $p)
   <tr>
   <td>{{ $p->purchase->user->Last_Name.', '.$p->purchase->user->First_Name }}</td>
   <td>{{ $p->purchase->user->Email }}</td>
   <td>{{ $p->purchase->productInstance->product->Name }}</td>
   <td>{{ $p->purchase->Purchase_Date  }}</td>
   <td>{{ $p->Payment_Date  }}</td>
   <td>{{ $p->lastHistory()->Process_Time }}</td>
   <td>{{ $p->lastHistory()->billingInformation->Payment_Type == PaymentType::PayPal ?     "PayPal" :
   CreditCardType::ToString($p->lastHistory()->billingInformation->CCType)." Ending In     ".$p->lastHistory()->billingInformation->CCLast4 }}</td>
   <td>{{ $p->lastHistory()->Trans_Response_Code }}</td>
   <td>{{ $p->lastHistory()->Trans_Response_Text }}</td>
   </tr>
@endforeach
</tbody>
</table>

1 个答案:

答案 0 :(得分:0)

首先我要说的是,我不会为您编写所有代码。这不是StackOverflow的目的......
但是我希望我能用这个答案指出你正确的方向 您的问题可以分为两个任务。一个是生成CSV文件,然后提供下载。

生成CSV文件

您会在互联网上找到很多代码段。这是我找到并修改了一下

的一个
$csvData = $yourCollection->toArray();
$filename = tempnam(sys_get_temp_dir(), 'csv_'); // create a temporary file in the system's default tmp directory
$file = fopen($filename, 'w');
foreach($csvData as $row){
    fputcsv($file, $row, ';'); // 3rd parameter is optional (default: ',')
}
fclose($file);

现在我们的temp文件夹中有一个csv文件,可以下载了。 Laravel为您提供了一种下载文件的方法。

提供文件供下载

在您的控制器操作中:

$response = Response::download($filename);
unlink($filename); // lets not forget to delete the file or they will pile up in your temp folder
return $response;

也许您还需要发送一些额外的标题(例如,用于指定用户看到的文件名),但我会将其留给您。

以下是对代码中使用的函数的一些引用:

相关问题