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.

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

报告相同问题?

悬赏问题

  • ¥15 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿