How to generate an Excel file with multiple sheets in PHP?

You can generate an Excel file in PHP using libraries like PhpSpreadsheet or SimpleXLSXGen. Below are the steps for both approaches.

1. Using PhpSpreadsheet (Recommended for complex spreadsheets)

PhpSpreadsheet is a powerful library for generating and manipulating Excel files.

Installation

First, install PhpSpreadsheet via Composer:
composer require phpoffice/phpspreadsheet

<?php
require ‘vendor/autoload.php’;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

// Set cell values
$sheet->setCellValue(‘A1’, ‘ID’);
$sheet->setCellValue(‘B1’, ‘Name’);
$sheet->setCellValue(‘A2’, ‘1’);
$sheet->setCellValue(‘B2’, ‘John Doe’);

$writer = new Xlsx($spreadsheet);

// Output to browser for download
header(‘Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’);
header(‘Content-Disposition: attachment;filename=”sample.xlsx”‘);
header(‘Cache-Control: max-age=0’);

$writer->save(‘php://output’);
exit;
?>