使用laravel将整个表导出为CSV

wwodge7n  于 2023-05-20  发布在  其他
关注(0)|答案(4)|浏览(177)

我是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

任何帮助将不胜感激。

lf3rwulv

lf3rwulv1#

简单的方法

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);
});
ql3eal8s

ql3eal8s2#

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->toArray());
    }
    fclose($file);
    return Redirect::to('consolidated');
}
gfttwv5a

gfttwv5a3#

选择查询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秒。

bvk5enib

bvk5enib4#

这样更好更简单。

$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');

相关问题