从数据库导出到xls(laravel 5)

时间:2016-04-26 09:56:02

标签: php excel laravel maatwebsite-excel

public function export(){
    view('tester');

    $assignments = DB::table('assignments')
        ->join('projects', 'assignments.project_id', '=', 'projects.id')
        ->join('people', 'assignments.person_id', '=', 'people.id')
        ->join('tasks', 'assignments.id', '=', 'tasks.assignment_id')
        ->select('assignments.*', 'projects.name','people.firstname','people.lastname', 'tasks.description','tasks.hours_spent')
        ->get();

    Excel::create('projects', function($excel) use($assignments) {
        $excel->sheet('Sheet 1', function($sheet) use($assignments) {
            $sheet->fromArray($assignments);
        });
    })->export('xls');


}

当我点击导出到xls

    <form class="form-horizontal" role="form" method="POST" action="{{action('ReportController@export')}}">

                        <input type="hidden" name="_token" value="{{ csrf_token() }}">  
                        <h4>Task Report</h4>
                        <button type="submit" class="btn btn-info btn-sm pull-right" style="margin-right: 10px">
                            Export to XLS format
                        </button>

错误是 DefaultValueBinder.php第65行中的ErrorException: 类stdClass的对象无法转换为字符串。请帮我解决这个问题。

3 个答案:

答案 0 :(得分:1)

试试这个简单明了: -

$assignments = json_decode( json_encode($assignments), true);

答案 1 :(得分:0)

$filename   = "Report-".date('d-m-Y').'_'.time();
Excel::create($filename, function($excel)use($record)  
      {
        $excel->sheet('Sheet 1', function($sheet)use($record)
    {
  $sheet->loadView('view', compact(array('record')));
    $sheet->setOrientation('portrait');
    });

})->export('xls');
exit();

还可以在<table>中创建视图并显示记录,但此视图不会调用任何布局部分

答案 2 :(得分:0)

如果我使用DB获取数据,我会收到错误....

DefaultValueBinder.php第65行中的ErrorException: 类stdClass的对象无法转换为字符串

$ret = Excel::create('statsExtract', function($excel) {
    $data = DB::table('thrps')->get();
    $excel->sheet('stats', function($sheet) use($data) {
        $sheet->fromArray($data);
    });
    })->download('xls');

如果我使用Eloquent模型提取.....它有效......

$ret = Excel::create('statsExtract', function($excel) {
    $data = Thrp::all();
    $excel->sheet('stats', function($sheet) use($data) {
        $sheet->fromArray($data);
    });
    })->download('xls');

但是,如果我尝试添加 - >&gt; leftJoin语句,我会收到一条错误,即leftJoin不存在....