How to export data to excel in PHP ?
Exporting data to Excel in PHP can be done using one popular library PhpSpreadsheet . Here’s a basic example of how to use PhpSpreadsheet to export data to Excel file:
1.Install PhpSpreadsheet :
You need to install PhpSpreadsheet via composer. Run the following command in your project directory:
composer require phpoffice/phpspreadsheet
2. Create and Export Excel File:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
//Create new spreadsheet object
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
//Sampple data
$data = [
['Name', 'Email', 'Age'],
['John Doe', 'john@example.com', 29],
['Steve Smith', 'steve@example.com', 34],
];
//Write data to the sheet
foreach ($data as $rowIndex => $row) {
foreach ($row as $colIndex => $cell) {
$sheet->setCellValueByColumnAndRow($colIndex + 1, $rowIndex + 1, $cell);
}
}
//Create a Writer and save the file
$writer = new Xlsx($spreadsheet);
$fileName = 'sample.xlsx';
//Save the file to the server
$writer->save($fileName);
//Optionally you can force download the file to the browser
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="'.$fileName.'"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit;
3. Explanation:
Ensure you have PhpSpreadsheet installed via Composer.
Create a new `Spreadsheet
` object and write data to it.
Save the excel file or download.