Skip to content

Merging cells in Excel by rows and columns together using PHPExcel

To merge cells in Excel using PhpSpreadsheet, you can use the mergeCells() method. Note: PHPExcel has been deprecated since 2015 and replaced by PhpSpreadsheet. The following examples use the modern library.

First, install the library via Composer:

bash
composer require phpoffice/phpspreadsheet

Example: Merging a rectangular range of cells

php
<?php

require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

// Merge cells A1 to C3 into a single cell
$sheet->mergeCells('A1:C3');

$writer = new Xlsx($spreadsheet);
$writer->save('merged_cells.xlsx');

This example merges the cells from A1 to C3 into one cell. You can specify any rectangular range using the 'StartCell:EndCell' format (e.g., 'A1:B2' or 'D5:F10').

Dual-run preview — compare with live Symfony routes.