首页 > 解决方案 > 在 Laravel 8 中导出到 excel 时添加列名

问题描述

我有这段代码以 excel 格式下载我的表,但是没有显示列名,因此不知道数据库的人无法读取数据。下载时有什么方法可以将列名添加到excel文档中?

这是我的代码:

用户导出.php

<?php

namespace App\Exports;

use App\User;
use App\Models\Models\Energy;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class UsersExport implements FromCollection
{

    public function collection()
    {
        return Energy::all();
    }       
}

能量控制器

public function export()
    {
 return Excel::download(new UsersExport, 'invoices.xlsx');

}

标签: phpmysqllaravellaravel-8maatwebsite-excel

解决方案


实现 WithHeadings,并将它们定义为一个数组:

class UsersExport implements FromCollection,WithHeadings {

      public function headings(): array {
          return [
              "name","mobile","email"
          ];
      }

..

检查这个例子: https ://makitweb.com/export-data-in-excel-and-csv-format-with-laravel-excel/


推荐阅读