PHPExcel为合并单元格设置AutoSize
未合并的代码
$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");
相关文章