没有任何建议对我有用,所以我进行了手动计算(相当简单和快速)(示例代码如下)并且效果很好(注意字体/样式是默认的,但很容易调整其他字体或样式)
foreach((array)$data as $sheet_data)
{
$maxwidth = array( );
$objPHPExcel->setActiveSheetIndex( $i++ );
$sheet = $objPHPExcel->getActiveSheet( );
if ( !empty($sheet_data['title']) )
$sheet->setTitle($sheet_data['title']);
if ( !empty($sheet_data['rows']) )
{
foreach((array)$sheet_data['rows'] as $row=>$cols)
{
foreach((array)$cols as $col=>$val)
{
$p = strpos($col,':');
if ( false !== $p )
{
// range
$range = $col; $xy = substr( $col, 0, $p );
$col = substr($xy,0,-1);
// estimate maximum column width by number of characters
$w = mb_strlen( $val );
if ( !isset($maxwidth[$col]) ) $maxwidth[$col] = $w;
elseif ( $w > $maxwidth[$col] ) $maxwidth[$col] = $w;
$sheet->mergeCells( $range );
$sheet->setCellValue( $xy, $val );
$sheet->getStyle( $range )
->getAlignment( )
->setHorizontal( PHPExcel_Style_Alignment::HORIZONTAL_CENTER )
->setVertical( PHPExcel_Style_Alignment::VERTICAL_CENTER )
;
}
else
{
$xy = $col.$row;
// estimate maximum column width by number of characters
$w = mb_strlen( $val );
if ( !isset($maxwidth[$col]) ) $maxwidth[$col] = $w;
elseif ( $w > $maxwidth[$col] ) $maxwidth[$col] = $w;
$sheet->setCellValue( $xy, $val );
$sheet->getStyle( $xy )
->getAlignment( )
->setHorizontal( PHPExcel_Style_Alignment::HORIZONTAL_CENTER )
->setVertical( PHPExcel_Style_Alignment::VERTICAL_CENTER )
;
}
}
}
}
// autosize columns based on calculation + some padding
foreach($maxwidth as $col=>$width)
{
$sheet->getColumnDimension( $col )->setAutoSize( false );
$sheet->getColumnDimension( $col )->setWidth( (int)($width * 1.2) ); // add padding as well
}
}