合并单元格的PHPExcel setAutoSize

时间:2014-01-24 12:47:37

标签: php phpexcel

没有合并的代码

$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

带合并的代码

$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

据我所知,没有标准方法为合并单元格设置自动大小。有没有解决方法呢?

2 个答案:

答案 0 :(得分:5)

您可以在使用->calculateColumnWidths()->setAutoSize(false)合并单元格之前计算列宽,以确保不再计算它们。代码可以 看起来像这样:

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

答案 1 :(得分:1)

我个人使用该值的大小来调整单元格的大小:

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

请注意,如果您在要修改的列上创建了->setAutoSize(true),则需要在进行任何修改之前将其置为false:

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