douxitao8170 2017-07-28 08:23
浏览 169
已采纳

使用Laravel 5.4导出CSV / XLSX

my post is too long but pls help me !

I tried to export data from database to CSV file, but I got 2 problems:

1. Update: I solved it by changing CSV to XLSX.

2. How can I get title_name in eloquent ? I tried but it did not work.

$title_japan = TitleJapan::select('id','name',$this->title->name)->get();

Here is my TitleJapan model:

    class TitleJapan extends Model
{
    public function title()
    {
        return $this->belongsTo('App\Title');
    }
}

Here is my Title model:

    class Title extends Model
{
    public function titleJapan()
    {
        return $this->hasMany('App\TitleJapan');
    }

}

And my controller:

    class ExportController extends Controller
{
    public function index()
    {
        return view('Export.index');
    }

    public function exportTitleCSV()
    {
        $title = Title::all();
        $title_japan = TitleJapan::select('id','name',$this->title->name)->get();

        return Excel::create('Filename', function($excel) use ($title,$title_japan,$title_oversea) {

            $excel->setTitle('TitleBandai');
            $excel->sheet('FirstSheet', function($sheet) use($title_japan) {
                $sheet->fromArray($title_japan);
            });
            $excel->sheet('SecondSheet', function($sheet) use($title_oversea) {
                $sheet->fromArray($title_oversea);
            });

        })->export('csv');
    }
}

File CSV I got

enter image description here

File CSV I want

enter image description here

  • 写回答

1条回答 默认 最新

  • duangu3620 2017-07-28 08:37
    关注

    A .csv file is very simple. It's just some data separated by commas or some other delimiter. Therefore, it cannot have multiple sheets. If you export as .xlsx it should work.

    For the name of the title, i suggest you eager load the title and then process the result into an array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?