laravel 导出 excel 实现自适应宽高,并自动换行
首先肯定要安装composer 依赖包,这里我就不写了,直接上代码
下面展示一些 内联代码片
。
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Worksheet\ColumnDimension;
class YourController implements FromArray, WithHeadings, WithTitle, WithEvents
{
protected $array;
public function __construct($arrayinfo)
{
$this->array= $arrayinfo;
}
/*
* 导出的数据
* */
public function array(): array
{
return $this->array;
}
/*
* 定义EXCEL表头
* */
public function headings(): array
{
return [
'表头1',
'表头2',
'表头3'
];
}
/**
* 设置excel的样式
* @return mixed
*/
public function registerEvents(): array
{
return [
AfterSheet::class => function(AfterSheet $event) {
//设置B列宽度
// $event->sheet->getColumnDimension('B')->setWidth(30);
// 设置B列的宽度自适应内容宽度
$event->sheet->getColumnDimension('B')->setAutoSize(true);
$highestRow = count($this->array) + 1; // 假设数组索引从0开始,所以加1得到总行数
$sheet = $event->sheet;
// 遍历E列的每一行并设置wrapText为true
for ($row = 1; $row <= $highestRow; $row++) {
//设置文本换行功能
//因为没有整列换行的功能,需要遍历为每一行换行
$sheet->getStyle('B' . $row)->getAlignment()->setWrapText(true);
}
// 如果你需要设置行高,你需要手动计算并设置
// 例如,设置第一行的高度
// $event->sheet->getRowDimension(1)->setRowHeight(30);
},
];
}
}