Search code examples
phpphpexcelphpspreadsheet

PHP SpreadSheet can't find the function to auto size column width


I simply want the columns to autosized. I am using php spreadsheet and I can't find how to do it. Any advise ? This is my code

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Projects First Year');
$sheet->setCellValue('B1', 'Grades');

$sheet->setCellValue('A2', 'PHP Project 2020');
$sheet->setCellValue('B2', $_SESSION['phpScore']);

Solution

  • Don't use range(). It won't work when cells beyond Z. Use instead

    foreach ($sheet->getColumnIterator() as $column) {
       $sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true);
    }