Merge Cells In Excel Files In PHP Using PHPSpreadSheet

| June 27, 2020 | 6,197 views | PhpSpreadsheet

Using the generated file from the tutorial Create Xlsx Files With Different Cell Background Colors, learn how to merge cells in PhpSpreadsheet.


  • Composer
  • PHP 7.2 or newer

Before Cell Merging

Step 1.

Setup dependencies.

    "require": {
        "phpoffice/phpspreadsheet": "^1.3"

Step 2.

Install phpspreadsheet.

$ composer install

Step 3.

Create a new PHP file, and start coding.


// Autoload dependencies
require 'vendor/autoload.php';

// Import the IOFactory class
use \PhpOffice\PhpSpreadsheet\IOFactory;

// Import the Xlsx writer class
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// Full path of the file to be indentified
$inputFileName = 'create-xlsx-files-with-different-cell-background-colors.xlsx';

// Identify the file type using the IOFactory object
$inputFileType = IOFactory::identify($inputFileName);

// Create the reader object
$reader = IOFactory::createReader($inputFileType);

// Load the file to read
$spreadsheet = $reader->load($inputFileName);

// Retrieve the current active worksheet
$sheet = $spreadsheet->getActiveSheet();

// Merge cells from A1 to D5

// Write a new .xlsx file
$writer = new Xlsx($spreadsheet);

// Save the new .xlsx file


Run the following codes.

$ php merge-cells-in-xlsx-files.php


Open the generated file merge-cells-in-xlsx-files.xlsx.



Leave a Reply

Your email address will not be published.