Merge Cell values with PHPExcel - PHP

Merge Cell values with PHPExcel - PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Merging First and Last Names in PHPExcel

When exporting tabular data to XLS format using the PHPOffice/PHPExcel library, a common requirement is consolidating logical fields into a single visual unit. Consider a dataset containing an id, first_name, last_name, email, and phone. If you populate the worksheet row by row, placing the first name in column B and the last name in column C, the resulting spreadsheet displays two distinct cells side-by-side. To achieve a single header or merged value spanning these columns, you must explicitly invoke the merge functionality after populating the relevant cells.

The core mechanism in PHPOffice/PHPExcel for this operation is the mergeCells method on the worksheet object. This method does not automatically combine content; it simply removes the borders between specified cell ranges, causing them to render as one block. The syntax requires a string argument representing the range, formatted as "StartCell:EndCell". For instance, merging columns B and C for row 1 uses the range "B1:C1".

To implement this within your existing data fetching loop, you must ensure the cells are populated before attempting to merge them. While PHPOffice/PHPExcel allows setting values via chained calls, it is often clearer to separate the population logic from the styling logic. If you attempt to call mergeCells immediately after setting a value without ensuring the worksheet instance is correctly initialized or if you mix legacy mysql_fetch_row with modern object-oriented practices, runtime errors can occur. The library expects valid cell references and a properly instantiated PHPExcel_Worksheet object.

Here is how you might structure the code to achieve the desired layout while maintaining data integrity:

$rowNumber = 1;
while ($row = mysql_fetch_row($result)) {
    $objPHPExcel->getActiveSheet()->setCellValue('A' . $rowNumber, $row['id']);
    $objPHPExcel->getActiveSheet()->setCellValue('B' . $rowNumber, $row['first_name'] . ' ' . $row['last_name']);
    
    // Option 1: Merge cells and set the combined value
    // $objPHPExcel->getActiveSheet()
    //     ->mergeCells('B' . $rowNumber . ':C' . $rowNumber)
    //     ->setCellValue('B' . $rowNumber, $row['first_name'] . ' ' . $row['last_name']);

    // Option 2: Set individual values then merge (if you need to keep them separate for other reasons)
    // $objPHPExcel->getActiveSheet()
    //     ->setCellValue('B' . $rowNumber, $row['first_name'])
    //     ->setCellValue('C' . $rowNumber, $row['last_name'])
    //     ->mergeCells('B' . $rowNumber . ':C' . $rowNumber);

    $col = 'D'; // Skip B and C if using Option 1, or continue from E for email/phone
    $objPHPExcel->getActiveSheet()->setCellValue($col . $rowNumber, $row['email']);
    $objPHPExcel->getActiveSheet()->setCellValue(($col++) . $rowNumber, $row['phone']);

    $rowNumber++;
}

A critical trade-off to consider is the preservation of column widths. When you merge cells in PHPOffice/PHPExcel, the width of the merged area defaults to the width of the first cell in the range (in this case, column B). If column C was wider than column B, the visual representation will be truncated or misaligned unless you manually adjust the column width using getActiveSheet()->getColumnDimension('B')->setWidth($width);.

Additionally, be aware that merging cells can affect sorting and filtering operations if your application relies on those features. Merged ranges are treated as a single unit; clicking inside the merged cell typically selects the entire range, which might interfere with row-level interactions in Excel or compatible viewers. If you require both a merged display for headers but distinct data handling, consider using conditional formatting or explicit borders rather than merging content rows.

For developers transitioning from legacy MySQL functions to modern stacks, note that mysql_fetch_row is deprecated as of PHP 5.5 and removed in PHP 7.0. While the PHPOffice/PHPExcel library itself remains a popular tool for XLS generation, ensuring your data access layer uses mysqli or PDO is essential for maintaining security and compatibility with current PHP versions. Resources like https://laravelcompany.com often discuss modernizing legacy PHP applications, including updating deprecated database extensions while refactoring existing export logic to use more robust libraries like PHPSpreadsheet (the successor to PHPExcel), which offers improved performance and memory management for large datasets.

Ultimately, the solution involves calling mergeCells with the correct range string immediately after setting the cell values. This approach respects the library's API constraints while delivering the expected visual output in the generated XLS file.

Our network