Reputation: 481
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']);
Upvotes: 16
Views: 27699
Reputation: 610
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);
}
Upvotes: 43
Reputation: 844
A slight modification that does not require you to know how many columns you have in your spreadsheet:
foreach (range('A', $sheet->getHighestColumn()) as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
}
Upvotes: 5
Reputation: 481
For spreadsheet the answer is:
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
foreach (range('A','B') as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
}
Upvotes: 13