问题描述
我正在尝试自动调整工作表的列大小.我正在写文件,最后尝试调整所有列的大小.
I'm trying to auto size the columns of my sheet.I'm writing the file and in the end I try to resize all of my columns.
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('B1', 'test1111111111111111111111')
->setCellValue('C1', 'test1111111111111')
->setCellValue('D1', 'test1111111')
->setCellValue('E1', 'test11111')
->setCellValue('F1', 'test1')
->setCellValue('G1', 'test1');
foreach($objPHPExcel->getActiveSheet()->getColumnDimension() as $col) {
$col->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->calculateColumnWidths();
上面的代码不起作用.不会更改列的大小以适合文本
The above code doesn't work. Doesn't change the column size to fit the text
更新我正在使用的作家$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
UPDATEThe writer I'm using $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
推荐答案
如果将列设置为AutoSize,PHPExcel会尝试根据列的计算值(因此根据任何公式的结果)来计算列宽,以及格式掩码(例如千位分隔符)添加的任何其他字符.
If a column is set to AutoSize, PHPExcel attempts to calculate the column width based on the calculated value of the column (so on the result of any formulae), and any additional characters added by format masks such as thousand separators.
默认情况下,这是estimated
宽度:基于使用GD的更精确的计算方法是可用的,它还可以处理字体样式功能,例如粗体和斜体;但这是一个大得多的开销,因此默认情况下将其关闭.您可以使用
By default, this is an estimated
width: a more accurate calculation method is available, based on using GD, which can also handle font style features such as bold and italic; but this is a much bigger overhead, so it is turned off by default. You can enable the more accurate calculation using
PHPExcel_Shared_Font::setAutoSizeMethod(PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT);
但是,自动调整大小并不适用于所有Writer格式...例如CSV.您没有提到您正在使用的作家.
However, autosize doesn't apply to all Writer formats... for example CSV. You don't mention what writer you're using.
但是您还需要标识列以设置尺寸:
But you also need to identify the columns to set dimensions:
foreach(range('B','G') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)
->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->getColumnDimension()
需要一个列ID.
$objPHPExcel->getActiveSheet()->getColumnDimensions()
将返回所有已定义列维记录的数组;但是除非明确创建了列维记录(例如通过加载模板或通过手动调用getColumnDimension()
),否则该记录将不存在(保存内存).
$objPHPExcel->getActiveSheet()->getColumnDimensions()
will return an array of all the defined column dimension records; but unless a column dimension record has been explicitly created (perhaps by loading a template, or by manually calling getColumnDimension()
) then it won't exist (memory saving).
这篇关于PHPExcel自动调整栏宽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!