Write Data to MS Excel (XLSX) File using PHP

phpoffice/phpspreadsheet library

  1. Add phpoffice/phpspreadsheet library to composer.json file:
"require": {
    "phpoffice/phpspreadsheet": "^1.14"
}
  1. Install library from the command line:
composer install
  1. 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

Your email address will not be published.