微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在 Laravel 8 中导出到 excel 时添加列名

我有代码以 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');

}

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。