Am使用Laravel Excel 3.1版生成CSV / XLS等。 我必须自定义csv或xls,以使自定义页脚和页眉跨列。
它看起来应该像所附的屏幕截图中一样。
此外,我想将导出的文件存储到存储位置,但是无法正常工作。
我完成的代码是:
class ReportExport implements FromArray, WithHeadings
{
protected $results;
public function __construct(array $results, array $headings, array $fileAttributes)
{
$this->results = $results;
$this->headings = $headings;
$this->file_attributes = $fileAttributes;
}
/**
* @return array
*/
public function array(): array
{
return $this->results;
}
/**
* @return array
*/
public function headings(): array
{
return $this->headings;
}
public function registerEvents(): array
{
return [
// Handle by a closure.
BeforeExport::class => function(BeforeExport $event) {
$event->writer->getProperties()->setTitle('Patrick');
},
];
}
}
按以下方式呼叫我
:Excel::store(["1","2"],"xyz.xlsx");
如何将这些额外的行添加到导出的结果中。
答案 0 :(得分:2)
Laravel Excel-扩展
https://docs.laravel-excel.com/3.1/exports/extending.html
PHPSpreadsheet
https://phpspreadsheet.readthedocs.io/en/latest/
有一些清理空间,但这应该为您提供基础知识。
public function registerEvents(): array
{
return [
// Handle by a closure.
AfterSheet::class => function(AfterSheet $event) {
// last column as letter value (e.g., D)
$last_column = Coordinate::stringFromColumnIndex(count($this->results[0]));
// calculate last row + 1 (total results + header rows + column headings row + new row)
$last_row = count($this->results) + 2 + 1 + 1;
// set up a style array for cell formatting
$style_text_center = [
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER
]
];
// at row 1, insert 2 rows
$event->sheet->insertNewRowBefore(1, 2);
// merge cells for full-width
$event->sheet->mergeCells(sprintf('A1:%s1',$last_column));
$event->sheet->mergeCells(sprintf('A2:%s2',$last_column));
$event->sheet->mergeCells(sprintf('A%d:%s%d',$last_row,$last_column,$last_row));
// assign cell values
$event->sheet->setCellValue('A1','Top Triggers Report');
$event->sheet->setCellValue('A2','SECURITY CLASSIFICATION - UNCLASSIFIED [Generator: Admin]');
$event->sheet->setCellValue(sprintf('A%d',$last_row),'SECURITY CLASSIFICATION - UNCLASSIFIED [Generated: ...]');
// assign cell styles
$event->sheet->getStyle('A1:A2')->applyFromArray($style_text_center);
$event->sheet->getStyle(sprintf('A%d',$last_row))->applyFromArray($style_text_center);
},
];
}
编辑:基本页面格式
这里有一些额外的功能可帮助您进行输出格式化。这些可以附加到现有的 AfterSheet 事件中。您可能需要打开另一个有关PDF操作细节的问题。
// set columns to autosize
for ($i = 1; $i <= count($this->results[0]); $i++) {
$column = Coordinate::stringFromColumnIndex($i);
$event->sheet->getColumnDimension($column)->setAutoSize(true);
}
// page formatting (orientation and size)
$event->sheet->getPageSetup()->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);
$event->sheet->getPageSetup()->setPaperSize(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LETTER);