43
votes

I have a simple table like:


- id 
- first_name
- last_name
- email
- phone

I'm using PHPExcel to export my data in XLS format


    $rowNumber = 1;
    while ($row = mysql_fetch_row($result)) {
       $col = 'A';
       foreach($row as $cell) {
          $objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
          $col++;
       }
       $rowNumber++;
   }

Now I want to merge the two fields first_name & last_name in one Cell

I tried:


$rowNumber = 1;
   while ($row = mysql_fetch_row($result)) {
   $objPHPExcel->getActiveSheet()->setCellValue('A'.$rowNumber,$row['id'])
                                 ->setCellValue('B'.$rowNumber,$row['first_name'])
                                 ->setCellValue('C'.$rowNumber,$row['last_name']);                                                                  
   $rowNumber++;
}

But I get errors and don't works. Any help?

3
Jared Farrish >> something like: dpaste.de/uXbH/raw - Cheerio
It looks like your headers aren't working. Make sure they are before any output whatsoever (even whitespace). - Jared Farrish
If you have Firebug or Chrome, you can also use the NET tab to inspect the headers that your browser is seeing. But from what that looks like, your browser seems to think it's plaintext and is trying to display it like a plaintext document. - Jared Farrish

3 Answers

107
votes

There is a specific method to do this:

$objPHPExcel->getActiveSheet()->mergeCells('A1:C1');

You can also use:

$objPHPExcel->setActiveSheetIndex(0)->mergeCells('A1:C1');

That should do the trick.

17
votes

Try this

$objPHPExcel->getActiveSheet()->mergeCells('A1:C1');
3
votes

$this->excel->setActiveSheetIndex(0)->mergeCells("A".($p).":B".($p)); for dynamic merging of cells