在Laravel 8中导出到excel时添加列名

iovurdzv  于 2023-01-31  发布在  其他
关注(0)|答案(2)|浏览(169)

我有这段代码,下载我的表格在excel格式,但列名不显示,所以数据是不可读的人谁不知道数据库。有什么办法添加列名到excel文档下载时?
下面是我的代码:
UsersExport.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');

}
hfyxw5xn

hfyxw5xn1#

实现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/

xkftehaa

xkftehaa2#

在FormCollection之后实现WithHeadings并定义标头。

<?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, WithHeadings
    {
        public function collection()
        {
            return Energy::all();
        }
    
        public function headings(): array
        {
            return ["First Name", "Last Name", "Contact", "Address", "Gender"];
        }
    }

相关问题