- Add
phpoffice/phpspreadsheet
library to composer.json
file:
"require": {
"phpoffice/phpspreadsheet": "^1.14"
}
- Install library from the command line:
composer install
- Write data to MS Excel (XLSX) file:
<?php
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
require_once __DIR__.'/vendor/autoload.php';
$data = [
['John', 25],
['Mary', 30],
['Robert', 42],
];
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$row = 1;
foreach ($data as $item) {
$sheet->setCellValueByColumnAndRow(1, $row, $item[0]);
$sheet->setCellValueByColumnAndRow(2, $row, $item[1]);
$row++;
}
$writer = new Xlsx($spreadsheet);
$writer->save('test.xlsx');
Leave a Comment
Cancel reply