How to PHPExcel set auto-columns width

北战南征 提交于 2019-12-03 08:17:31

问题


I'm working with PHPExcel to export data for download. When open downloaded files, with cells have big number, it show "#######" instead of value number. I'm tried setAutoSize() for every columns then call $sheet->calculateColumnWidths() but it still not changes. I see calculateColumnWidths() at here, @Mark Baker says "calculateColumnWidths() increase the value by perhaps 5% to try and ensure that the entire column fits". If number length in cell exceed 5%, it seems doen's resolved the problem

UPDATE This is my function to auto size columns:

   function autoFitColumnWidthToContent($sheet, $fromCol, $toCol) {
        if (empty($toCol) ) {//not defined the last column, set it the max one
            $toCol = $sheet->getColumnDimension($sheet->getHighestColumn())->getColumnIndex();
        }
        for($i = $fromCol; $i <= $toCol; $i++) {
            $sheet->getColumnDimension($i)->setAutoSize(true);
        }
        $sheet->calculateColumnWidths();
    }

回答1:


First potential problem may be that you're working with column letters. PHP's incrementor operation will work with column letters, so if $i is 'A', then $i++ will give 'B', and if $i is 'Z' than $i++ will give 'AA'; but you can't use <= as your comparator, as 'AA' is <= 'Z' when executed as a straight comparison.

Instead of

for($i = $fromCol; $i <= $toCol; $i++) {

use

$toCol++;
for($i = $fromCol; $i !== $toCol; $i++) {

To add the 5% margin after calling $sheet->calculateColumnWidths() do:

for($i = $fromCol; $i !== $toCol; $i++) {
    $calculatedWidth = $sheet->getColumnDimension($i)->getWidth();
    $sheet->getColumnDimension($i)->setWidth((int) $calculatedWidth * 1.05);
}



回答2:


None of the suggestions worked for me so i did a manual calculation (rather easy and fast) (sample code follows) and works perfectly (note fonts/styles are default but it would be easy to adjust for other font or style)

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
    }
}


来源:https://stackoverflow.com/questions/10927462/how-to-phpexcel-set-auto-columns-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!