使用laravel将整个表导出为CSV

时间:2013-04-16 11:39:59

标签: php csv export laravel-3 fputcsv

我是laravel的新手,并且很难找到将一个表导出到csv的方法。 我在控制器类中尝试了以下代码,但它给了我一个错误:

    public function get_export()
{
    $table = Cpmreport::all();
    $file = fopen('file.csv', 'w');
    foreach ($table as $row) {
        fputcsv($file, $row);
    }
    fclose($file);
    return Redirect::to('consolidated');
}

Cpmreport的模型类:

    class Cpmreport extends Eloquent
    {
      public static $table='cpm_report';
    }

错误:

    Message:

    fputcsv() expects parameter 2 to be array, object given

    Location:

    C:\xampp\htdocs\cpm_report\application\controllers\cpmreports.php on line 195

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分:20)

简单方法

Route::get('/csv', function() {
  $table = Cpmreport::all();
  $output='';
  foreach ($table as $row) {
      $output.=  implode(",",$row->toArray());
  }
  $headers = array(
      'Content-Type' => 'text/csv',
      'Content-Disposition' => 'attachment; filename="ExportFileName.csv"',
  );

  return Response::make(rtrim($output, "\n"), 200, $headers);
});

答案 1 :(得分:7)

fputcsv($file, $table);应为fputcsv($file, $row),不是吗?

使用Eloquent的to_array()方法将对象转换为数组:http://laravel.com/docs/database/eloquent#to-array

public function get_export()
{
    $table = Cpmreport::all();
    $file = fopen('file.csv', 'w');
    foreach ($table as $row) {
        fputcsv($file, $row->to_array());
    }
    fclose($file);
    return Redirect::to('consolidated');
}

答案 2 :(得分:2)

选择MySQL数据查询。

$data = \DB::connection('mysql')->select($select);

调用以下功能:

query_to_csv($data, 'data.csv');

function data_to_csv($data, $filename)
    {
        $fp = fopen($filename, 'w');
        foreach ($data as $row) {
            fputcsv($fp, $row);
        }

        fclose($fp);
    }

0.1百万条记录需要1秒才能创建。

答案 3 :(得分:-1)

这更好,更简单。

$file_name = "abc";
$postStudent = Input::all();
$ck = DB::table('loan_tags')->select('LAN')->where('liabilitiesId', $postStudent['id'])->get();
$i = 0;
foreach ($ck as $row) { 

              $apps[$i]['LAN'] = $row->LAN;
            $apps[$i]['Account_number'] =   $postStudent['account_number'];
            $apps[$i]['Bank_Name'] =  $postStudent['bank_name'];
            $i++;
}

ob_end_clean();
ob_start();
Excel::create($file_name, function($excel) use($apps){
        $excel->sheet('Sheetname', function($sheet) use($apps){

           $sheet->row(1, array(
                 'LAN', 'Account number' , 'Bank Name'
            ));
            $k = 2;
             foreach ($apps as $deta) {
                 $sheet->row($k, array($deta['LAN'],   $deta['Account_number'], $deta['Bank_Name']
                ));
                $k++;
             }
        });
    })->download('xlsx');