简体   繁体   中英

PHPExcel setAutoSize for merged cells

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");

在此输入图像描述

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");

在此输入图像描述

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

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");

i personnaly used the size of the value to adapt the size of the cell :

$value =  $sheet->getCell('A1')->getValue();
$width = mb_strwidth ($value); //Return the width of the string
$sheet->getColumnDimension('A')->setWidth($width);

Beware if you have made a ->setAutoSize(true) on the column that you want to modify you need to put it at false before doing any modifications :

$sheet->getColumnDimension('A')->setAutoSize(false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM