rap2hpoutre / fast-excel

🦉 Fast Excel import/export for Laravel
MIT License
2.09k stars 246 forks source link

How to merge cells? #296

Open afiqiqmal opened 1 year ago

afiqiqmal commented 1 year ago

I see that box spout has merge cell function but i can't figure it out where to customize it in fast-excel. How to merge cell in fast-excel?

HussamAlhennawi commented 7 months ago

Here is a workaround solution by using configureOptionsUsing() with a callback.

You can use mergeCells() function from vendor\openspout\openspout\src\Writer\XLSX\Options.php:

public function mergeCells(
    int $topLeftColumn,
    int $topLeftRow,
    int $bottomRightColumn,
    int $bottomRightRow,
    int $sheetIndex = 0,
)

Example:

$firstRow = [
    "First Column",     // will be merged vertically with the cell below it
    "Second Column",    // will be merged horizontally with the right cell
    "",                 // this value will be ignored after merge
    "Fourth Column",    // will be merged horizontally with the right cell
    ""                  // this value will be ignored after merge
];

$excelRows = collect([$firstRow, ...]);

return (new FastExcel($excelRows))
    ->configureOptionsUsing(function ($options) {
        $options->mergeCells('0', '1', '0', '2');
        $options->mergeCells('1', '1', '2', '1');
        $options->mergeCells('3', '1', '4', '1');
    })
    ->withoutHeaders();

Tip: In the mergeCells() parameters the rows started from 1 and columns from 0.

The result will be like this:

Merge Cells