Archive for November, 2020


Merge Excel Sheets with Laravel Excel

Laravel Excel allows you to create and format Excel documents with PHP within the Laravel framework.  I specifically needed to merge Excel sheets, and not just tack on the sheets to one document, but actually merge several files into a single sheet.  It’s pretty straightforward, but the documentation leaves a bit to be desired so it took me a while to narrow down the right way to do this.  The only downside is it will remove any formatting from the sheets.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//first pull all the rows
$rows = [];
Excel::batch(storage_path('FOLDER/CONTAINING/EXCEL/FILES'), function($rows1, $file) use($rows) {
    $rows1->each(function($row) use($rows1) {
        global $rows;
 
        $rows[] = $row->toArray();
    });
 
});
 
//then add them to a new file
Excel::create('new_filename', function ($excel) use ($rows) {
    $excel->sheet('Sheet', function ($sheet) use ($rows) {
        global $rows;
 
        // Sheet manipulation
        foreach($rows as $row) {
            $sheet->appendRow($row);
        }
    });
})->store('xls', storage_path('excel/exports'));

Permalink » No comments