【问题标题】:How to change columns names in Excel Laravel?如何更改 Excel Laravel 中的列名称?
【发布时间】:2022-01-14 08:54:01
【问题描述】:

我使用this library 将数据从集合导出到 excel 文件。默认情况下,我将列名称设置为表字段的名称。

如何自行替换列名?

我有自己的抽象类:

abstract class Excel
{ 
    
    abstract public function export();

    public function download()
    {
        $this->file = \Excel::create($this->filename, function ($excel) {
            $excel->sheet($this->sheetname, function ($sheet) {
                $sheet->fromArray($this->data->toArray());
            });
        })->store($this->typefile, $this->path_save);
    }

}

我的excel文件:

<?php

    namespace App\Library;
    
    use App\Library\Excel;
    use App\DistributorContacts;
    use App\PersonalityTraits;
    use App\Helpers\Helper;
    use Maatwebsite\Excel\Concerns\WithHeadings;
    
    
    class ExcelConclusions extends Excel implements WithHeadings
    {
    
    
        public $type = "_conclusions";
    
    
        public function headings(): array
        {
            return ["your", "headings", "here"];
        }
    
        public function export()
        {}
    }

【问题讨论】:

标签: laravel laravel-excel


【解决方案1】:

在你的导出类中使用这样的界面标题:

namespace App\Exports;

use App\NameOfTable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class NameOfExport implements FromCollection , WithHeadings{

    public function collection()
    {
        return NameOfTable::get();
    }

     public function headings():array
        {
            return [
                'NameOfFirstColumn',
                'NameOfSecondColumn,
        ....
        
            ];
        } 
}

您应该定义所有导出的列。

我有一个控制器 ExportExcel,它调用定义为 Exports 类的导出

<?php

namespace App\Http\Controllers;

use App\Exports\nameOfExpport;
use Maatwebsite\Excel\Facades\Excel;

    class ExportExcel extends Controller
    {
        //
        public function functionName() {
            return Excel::download(new nameOfExpport() , 'fileName');
        }

.....

【讨论】:

  • 我应该实现接口吗?
  • 我已经编辑了我的答案,请看看它是否有效....
  • 如果有帮助,请选择此作为答案(答案下方的复选标记):)
  • 你能提供进口吗?
  • 我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-20
  • 2020-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-17
相关资源
最近更新 更多