Laravel-excel: How can i merge two xlsx files and download the combined one?

Created on 9 Oct 2017  ·  3Comments  ·  Source: Maatwebsite/Laravel-Excel

Please prefix your issue with one of the following: [BUG] [PROPOSAL] [QUESTION].

Package version, Laravel version

Expected behaviour

Actual behaviour

Exception stack trace

Screenshot of Excel file

Steps to reproduce the behaviour

Most helpful comment

@sarpkaya-xx try addSheet():

    Excel::create('workbook', function ($excel) {
        // Create first "original" sheet
        $original = $excel->sheet('Sheet 1', function ($sheet) {
            $sheet->fromArray([
                ['foo' => 'bar']
            ]);
        });
        // Copy the first sheet 4 times
        for ($sheetCount = 2; $sheetCount <= 5; $sheetCount++) {
            $copy = $original->getSheet()->copy();
            $copy->setTitle("Sheet {$sheetCount}");
            $excel->addSheet($copy);
        }
    })->save();

All 3 comments

Hi @kurianic, the example below will read all the sheets from workbooks A and B, and copy them to a new workbook C. Please ensure A and B do not contain sheets with the same name.

// Load the workbooks to merge in a collection.
// This example is assuming they're stored in the Laravel storage folder.
$workbooks = collect([
    'workbookA.xlsx',
    'workbookB.xlsx',
])->map(function ($filename) {
    return Excel::load(storage_path($filename));
});

// Create merged workbook
$workbookC = Excel::create('workbookC', function ($excel) use ($workbooks) {
    // For each workbook to be merged
    $workbooks->each(function ($workbook) use ($excel) {
        // Get all the sheets
        collect($workbook->getAllSheets())->each(function ($sheet) use ($excel) {
            // And add them to the merged workbook
            $excel->addExternalSheet($sheet);
        });
    });
})->save(); // save merged workbook to storage/exports/workbookC.xlsx

Hi @stephanecoinon , I want to add the same sheet multiple times, to prevent duplicated names, I called $sheet->setTitle. but it gives me an error "Sheet does not exist." when addExternalSheet called just after setTitle.

$sheet_original->setTitle("SHEET ".$i); $sheets[$i] = $sheet_original; $sheets[$i]->cell('I64', function($cell) use($i) { $cell->setValue($i); }); $excel->addExternalSheet($sheets[$i] );

@sarpkaya-xx try addSheet():

    Excel::create('workbook', function ($excel) {
        // Create first "original" sheet
        $original = $excel->sheet('Sheet 1', function ($sheet) {
            $sheet->fromArray([
                ['foo' => 'bar']
            ]);
        });
        // Copy the first sheet 4 times
        for ($sheetCount = 2; $sheetCount <= 5; $sheetCount++) {
            $copy = $original->getSheet()->copy();
            $copy->setTitle("Sheet {$sheetCount}");
            $excel->addSheet($copy);
        }
    })->save();
Was this page helpful?
0 / 5 - 0 ratings