Write Excel Reports
Create a production-ready XLSX report from PHP data, add a header, improve navigation, and save it to an application-controlled path.
Updated
PHP 8.1+Full packageNative XLSX
MnbExcel::report()WorkbookBuilder::withHeader()WorkbookBuilder::freezeHeader()WorkbookBuilder::autoFilter()WorkbookBuilder::save()What you will learn
- Create a report from associative application rows.
- Apply useful report defaults without manual OOXML work.
- Save generated output to a controlled application directory.
Install the full package#
composer require mnb/mnb-phpexcel:^2.0The report builder belongs to the main package and exposes a higher-level workflow than the individual format writers.
Create a complete report#
use Mnb\PHPExcel\MnbExcel;
$rows = [
['Order ID' => 'ORD-1001', 'Customer' => 'Arjun Stores', 'Amount' => 1250.50],
['Order ID' => 'ORD-1002', 'Customer' => 'Northwind Retail', 'Amount' => 899.00],
];
$path = MnbExcel::storagePath('exports', 'sales-report.xlsx');
MnbExcel::report($rows, template: 'business')
->title('Sales Report')
->withHeader()
->currencyColumns(['Amount'], '$')
->freezeHeader()
->autoFilter()
->autoWidth()
->save($path);
echo $path;Developer contract and expected workbook#
- Builder type
WorkbookBuilder- Chainable configuration
- Title, headers, number formats, frozen panes, filters, widths, styles, and security.
- Terminal operation
save($path)- Result
- A generated workbook at the application-controlled path.
- Memory behavior
- Depends on source size and builder options; use large export workflows for very large datasets.
- Errors
MnbExcelExceptionor filesystem exceptions when output cannot be created.
Expected output
sales-report.xlsx
Sheet: Report
Rows: 3 including the header
Frozen header: yes
Auto filter: yesOpen the generated workbook in Excel or LibreOffice as part of release testing.
Production notes#
- Generate filenames in the application; never concatenate a browser-supplied path.
- Store files outside the public web root and stream them through a controlled download response.
- Use known widths or a sample for very large exports because full auto-width scans data.
- Escape formula-like text when exporting untrusted values.
- Use a large export workflow when rows cannot safely be held in application memory.
Continue the workflow#
Was this guide useful?Use GitHub issues for corrections, missing examples, or unclear behavior.
Open an issue