PHP_XLSXWriter_plus
PHP_XLSXWriter_plus copied to clipboard
Add-on: The default and custom column size
This line:
fwrite($fd, '<col collapsed="false" hidden="false" max="1025" min="1" style="0" width="11.5"/>');
should be:
fwrite($fd, '<col collapsed="false" hidden="false" max="1025" min="1" style="0" width="11.5" customWidth="1"/>');
And if you want to set custom column size, this block:
fwrite($fd, '<cols>');
fwrite($fd, '<col collapsed="false" hidden="false" max="1025" min="1" style="0" width="11.5"/>');
fwrite($fd, '</cols>');
Should be:
// set width for cols
fwrite($fd, '<cols>');
fwrite($fd, '<col collapsed="false" hidden="false" max="1025" min="1" style="0" width="11.5" customWidth="1"/>');
if ($this->defaultStyle)
{
foreach ($this->defaultStyle as $key => $style)
{
if (isset($style['sheet']))
{
if ($style['sheet'] == $sheet_name)
{
if (isset($style['cols_width']))
{
foreach ($style['cols_width'] as $col_width)
{
fwrite($fd, '<col min="' . $col_width[0] . '" max="' . $col_width[1] . '" width="' . $col_width[2] . '" customWidth="1"/>');
}
}
}
}
}
}
fwrite($fd, '</cols>');
and in style array:
$style = [['cols_width' => [[1, 1, 20],[2, 2, 30]]],
I thought this was a nice change but took a different approach. I wanted to use separate variables from the style array, and I didn't want to bother with coordinating minimums and maximums.
- First add defaultColumnWidth and columnWidths variables and setting function.
protected $defaultColumnWidth = 11.5;
protected $columnWidths = array();
public function setDefaultColumnWidth($columnWidth){ $this->defaultColumnWidth = $columnWidth;}
// example: setColumnWidths(array(10,15,20,25));
public function setColumnWidths($columnWidths) { $this->columnWidths = $columnWidths;}
- Then use the following in the writeSheet function.
fwrite($fd, '<cols>');
// if columnWidths are defined fill XML dynamically
if(!empty($this->columnWidths)){
// pad with default column width if defaultStartCol > 0
if($this->defaultStartCol > 0){
fwrite($fd, '<col collapsed="false" hidden="false" max="'.$this->defaultStartCol.'" min="1" style="0" width="'.$this->defaultColumnWidth.'" customWidth="1"/>');
}
foreach($this->columnWidths as $k=>$v){
// use one-based index for column numbering
$idx = $this->defaultStartCol+$k+1;
fwrite($fd, '<col collapsed="false" hidden="false" max="'.$idx.'" min="'.$idx.'" style="0" width="'.$v.'" customWidth="1"/>');
}
// use default column width beyond defined columns
fwrite($fd, '<col collapsed="false" hidden="false" max="1025" min="'.($this->defaultStartCol+count($this->columnWidths)+1).'" style="0" width="'.$this->defaultColumnWidth.'" customWidth="1"/>');
// if no columnWidths define, use default column width
} else {
fwrite($fd, '<col collapsed="false" hidden="false" max="1025" min="1" style="0" width="'.$this->defaultColumnWidth.'" customWidth="1"/>');
}
fwrite($fd, '</cols>');