PHPExcel setAutoSize for merged cells

PHPphpexcel

Code without merge

$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();

$sheet->setCellValueByColumnAndRow(0, 1, 
        "test test test test test test test test");
$sheet->getColumnDimension('A')->setAutoSize(true);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("test.xlsx");

enter image description here

Code with merge

$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();

$sheet->setCellValueByColumnAndRow(0, 1, 
        "test test test test test test test test");
//this breaks the width calculation
$sheet->mergeCells('A1:B1');
$sheet->getColumnDimension('A')->setAutoSize(true);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("test.xlsx");

enter image description here

As far as I understand, there is no standard way to set auto size for merged cells. Is there any workaround for this?

Best Answer

You could calculate the column widths before merging the cells using ->calculateColumnWidths(), and then ->setAutoSize(false) to make sure that they are not calculated again. The code could look something like this:

// Set the data in the cells
$objPHPExcel->getActiveSheet()->fromArray($sheet, null, 'A1');

// Calculate the column widths
foreach(range('A', 'E') as $columnID) {
    $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->calculateColumnWidths();

// Set setAutoSize(false) so that the widths are not recalculated
foreach(range('A', 'E') as $columnID) {
    $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(false);
}

// Merge cells
$objPHPExcel->getActiveSheet()->mergeCells("A1:A5");
Related Topic