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.
2 Comments
Astrid
March 6, 2025Fantastic site you have here but I was curious about if
you knew of any community forums that cover the same topics talked about in this article?
I’d really love to be a part of group where I can get feedback from other knowledgeable individuals that share
the same interest. If you have any suggestions, please
let me know. Thanks!
Uta
March 9, 2025There is certainly a great deal to find out about this
topic. I really like all the points you have made.