本文介绍了如何使用PHPExcel设置自动列宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与PHPExcel一起导出数据以进行下载.当打开的已下载文件的单元格编号很大时,它会显示"#######"而不是值编号.我尝试对每列使用setAutoSize(),然后调用$sheet->calculateColumnWidths(),但它仍然没有改变.我在这里看到, ,@ Mark Ba​​ker说"calculateColumnWidths()通过也许要尝试5%以确保整个色谱柱都适合".如果单元格中的数字长度超过5%,似乎确实可以解决问题

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

更新这是我自动调整列大小的功能:

UPDATEThis 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();
    }

推荐答案

第一个潜在的问题可能是您正在使用列字母.PHP的增量运算将适用于列字母,因此,如果$ i为'A',则$ i ++将给出'B',如果$ i为'Z',则$ i ++将给出'AA';但是您不能使用< =作为比较器,因为直接进行比较时'AA'为< ='Z'.

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.

代替

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

使用

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

要在调用$ sheet-> calculateColumnWidths()之后添加5%的利润,请执行以下操作:

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

这篇关于如何使用PHPExcel设置自动列宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 09:54