合并单元格的PHPExcel setAutoSize

代码没有合并

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

合并代码

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

据我所知,没有标准的方法来设置合并单元格的自动大小.这有什么解决方法吗?

解决方法:

您可以在使用 – > 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");
上一篇:实例化phpExcel类, 导出Excel----数据


下一篇:填充与复制