Reading examples
Reading Excel examples, explained clearly.
Open a focused example to see the implementation path, copy-ready PHP, expected workbook behavior, and the production boundary that matters.
11examples in this category
21supported categories
5implementation paths
Monolithic library
Reading examples with copy-ready, production-minded PHP.
Each example identifies the exact methods it uses and can be opened independently from the right-side index.
- 11
- examples
- 26
- documented methods
MnbExcel::read()sheet()withHeaderRow()toArray()<?php
declare(strict_types=1);
/*
Summary:
Read one worksheet into associative PHP rows while skipping empty records and enforcing a safe
row limit.
Implementation note:
Use toArray() for small and normal worksheets. Run the large-file preflight before loading an
unknown or very large workbook into memory.
*/
use Mnb\PHPExcel\MnbExcel;
$workbookPath = __DIR__ . '/fixtures/students.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$rows = MnbExcel::read($workbookPath)
->sheet('Students')
->withHeaderRow()
->toArray([
'skip_empty_rows' => true,
'max_rows' => 5_000,
]);
foreach ($rows as $row) {
echo $row['student_id'] . ': ' . $row['name'] . PHP_EOL;
}Use the monolithic facade when the application needs the complete package.
<?php
declare(strict_types=1);
/*
Summary:
Read one worksheet into associative PHP rows while skipping empty records and enforcing a safe
row limit.
Implementation note:
Use toArray() for small and normal worksheets. Run the large-file preflight before loading an
unknown or very large workbook into memory.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/students.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$rows = Xlsx::read($workbookPath)
->sheet('Students')
->withHeaderRow()
->toArray([
'skip_empty_rows' => true,
'max_rows' => 5_000,
]);
foreach ($rows as $row) {
echo $row['student_id'] . ': ' . $row['name'] . PHP_EOL;
}Use the focused XLSX facade when the application needs only native XLSX support.
MnbExcel::read()sheetNames()sheet()toArray()<?php
declare(strict_types=1);
/*
Summary:
Discover worksheet names first, then select a sheet by name instead of relying on workbook
order.
Implementation note:
Named selection is safer when users can reorder worksheets. sheet() also accepts a one-based
sheet index.
*/
use Mnb\PHPExcel\MnbExcel;
$workbookPath = __DIR__ . '/fixtures/sales-workbook.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$workbook = MnbExcel::read($workbookPath);
$sheetNames = $workbook->sheetNames();
print_r($sheetNames);
$orders = $workbook
->sheet('Orders')
->withHeaderRow()
->toArray();detectHeader()autoDetectHeader()headerAtPhysicalRow()toArray()<?php
declare(strict_types=1);
/*
Summary:
Inspect a messy worksheet, report the likely header row and confidence, then read using semantic
header detection.
Implementation note:
For a fixed supplier format, headerAtPhysicalRow() is more deterministic. Automatic detection is
best for variable exports with titles or blank rows above the table.
*/
use Mnb\PHPExcel\MnbExcel;
$workbookPath = __DIR__ . '/fixtures/vendor-export.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$session = MnbExcel::read($workbookPath)
->sheet(1);
$detection = $session->detectHeader([
'header_detection_rows' => 30,
]);
printf(
"Header row: %d (confidence %.2f)\n",
$detection->row,
$detection->confidence
);
$rows = $session
->autoDetectHeader(sampleRows: 30, minimumConfidence: 0.45)
->toArray([
'strict_header_detection' => true,
'header_case' => 'snake',
]);range()projectColumns()withHeaderRow()selectColumns()<?php
declare(strict_types=1);
/*
Summary:
Limit the source range and project only required worksheet columns before converting rows to PHP
arrays.
Implementation note:
Source projection reduces parsing work. After headers are mapped, selectColumns() can filter by
normalized header names.
*/
use Mnb\PHPExcel\MnbExcel;
$workbookPath = __DIR__ . '/fixtures/products.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$rows = MnbExcel::read($workbookPath)
->sheet('Products')
->range(startRow: 1, endRow: 5_000, startColumn: 'A', endColumn: 'F')
->projectColumns(['A', 'B', 'F'])
->withHeaderRow()
->toArray();cell()rangeValues()calculatedCell()cellDetails()sheetMetadata()<?php
declare(strict_types=1);
/*
Summary:
Read direct cell values, ranges, calculated formulas, typed cell details, comments, hyperlinks,
and worksheet metadata.
Implementation note:
cellDetails() returns a typed CellSnapshot. Use sheetMetadata() or images() when non-tabular
workbook content matters to the application.
*/
use Mnb\PHPExcel\MnbExcel;
$workbookPath = __DIR__ . '/fixtures/finance-report.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$sheet = MnbExcel::read($workbookPath)
->sheet('Summary');
$title = $sheet->cell('B2');
$monthlyTotals = $sheet->rangeValues('D5:D16');
$calculatedTotal = $sheet->calculatedCell('D17');
$details = $sheet->cellDetails('D17');
$metadata = $sheet->sheetMetadata();
print_r([
'title' => $title,
'monthly_totals' => $monthlyTotals,
'formula' => $details->formula,
'cached_value' => $details->cachedValue,
'calculated_value' => $calculatedTotal,
'comments' => $details->comments,
'hyperlinks' => $details->hyperlinks,
'sheet_summary' => $metadata['summary'] ?? [],
]);MnbExcel::inspect()ReadSession::inspect()<?php
declare(strict_types=1);
/*
Summary:
Inspect file size, encryption state, worksheet metadata, package warnings, and validation errors
without converting worksheet cells into a complete PHP array.
Implementation note:
inspect() reads XLSX package structure, workbook relationships, worksheet dimensions, and safety
warnings. Pass a password in the options array to inspect an encrypted workbook.
*/
use Mnb\PHPExcel\MnbExcel;
$workbookPath = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$inspection = MnbExcel::inspect($workbookPath);
print_r([
'status' => $inspection['status'],
'file' => $inspection['file'],
'size_bytes' => $inspection['size_bytes'],
'encrypted' => $inspection['encrypted'],
'sheet_count' => count($inspection['sheets']),
'warnings' => $inspection['warnings'],
'errors' => $inspection['errors'],
]);MnbExcel::sheetNames()MnbExcel::inspect()<?php
declare(strict_types=1);
/*
Summary:
List worksheet names directly, then inspect visibility, dimensions, declared last rows and
columns, and physical row-tag counts.
Implementation note:
Worksheet dimensions are fast metadata and can include stale formatting. row_tag_count is a
physical XML-row count, not a normalized data-record count.
*/
use Mnb\PHPExcel\MnbExcel;
$path = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($path)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $path));
}
$names = MnbExcel::sheetNames($path);
$inspection = MnbExcel::inspect($path);
print_r($names);
foreach ($inspection['sheets'] as $sheet) {
printf(
"%s: %s, dimension %s, declared row %s, row tags %s\n",
$sheet['name'],
$sheet['state'],
$sheet['dimension'] ?? 'unknown',
$sheet['declared_last_row'] ?? 'unknown',
$sheet['row_tag_count'] ?? 'unknown'
);
}MnbExcel::inspect()ReadSession::inspect()<?php
declare(strict_types=1);
/*
Summary:
Select one worksheet from the inspection result and read its dimensions, hidden rows and
columns, merges, filters, and drawing flags.
Implementation note:
inspect() exposes package and worksheet metadata only. Use a reader session when the application
needs actual cell values or normalized business-record counts.
*/
use Mnb\PHPExcel\MnbExcel;
$workbookPath = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$inspection = MnbExcel::inspect($workbookPath);
$orders = null;
foreach ($inspection['sheets'] as $sheet) {
if ($sheet['name'] === 'Orders') {
$orders = $sheet;
break;
}
}
if ($orders === null) {
throw new RuntimeException('Orders worksheet was not found.');
}
print_r([
'dimension' => $orders['dimension'],
'declared_last_row' => $orders['declared_last_row'],
'declared_last_column' => $orders['declared_last_column'],
'row_tag_count' => $orders['row_tag_count'],
'hidden_row_count' => $orders['hidden_row_count'],
'hidden_column_count' => $orders['hidden_column_count'],
'has_merge_cells' => $orders['has_merge_cells'],
'has_auto_filter' => $orders['has_auto_filter'],
'has_drawing' => $orders['has_drawing'],
]);ReadSession::countRows()MnbExcel::sheetNames()<?php
declare(strict_types=1);
/*
Summary:
Stream normalized rows through the regular reader and count them without collecting the complete
workbook result in memory.
Implementation note:
countRows() uses the same header, empty-row, range, limit, and projection behavior as rows(). It
streams yielded records rather than calling toArray().
*/
use Mnb\PHPExcel\MnbExcel;
$path = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($path)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $path));
}
$filledRows = MnbExcel::read($path)
->sheet('Orders')
->withHeaderRow()
->countRows(['skip_empty_rows' => true]);
$allSheetCounts = [];
foreach (MnbExcel::sheetNames($path) as $name) {
$allSheetCounts[$name] = MnbExcel::read($path)
->sheet($name)
->withHeaderRow()
->countRows(['skip_empty_rows' => true]);
}
print_r(compact('filledRows', 'allSheetCounts'));ReadSession::sheetOrActive()ReadSession::sheetIfExists()ReadSession::activeSheet()<?php
declare(strict_types=1);
/*
Summary:
Accept a nullable worksheet input without hiding non-empty typos, then continue with the
workbook active sheet when no value was supplied.
Implementation note:
sheetOrActive() falls back only for null or an empty string. A non-empty unknown sheet still
throws a clear SheetSelectionException. Use sheetIfExists() for a completely non-throwing
lookup.
*/
$workbookPath = __DIR__ . '/fixtures/report.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
<?php
$requestedSheet = trim((string) ($_GET['sheet'] ?? ''));
$session = MnbExcel::read($workbookPath)
->sheetOrActive($requestedSheet)
->withHeaderRow(1);
foreach ($session->rows() as $row) {
print_r($row);
}ReadSession::isEmpty()ReadSession::hasRows()ReadSession::toArray()<?php
declare(strict_types=1);
/*
Summary:
Evaluate normalized rows after header and empty-row options, then materialize the result only
when data exists.
Implementation note:
isEmpty(), hasRows(), and assertHasRows() belong to ReadSession. toArray() is terminal and
returns a native PHP array.
*/
$workbookPath = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
<?php
$session = MnbExcel::read($workbookPath)
->sheet('Orders')
->withHeaderRow(1)
->withOptions(['skip_empty_rows' => true]);
if ($session->isEmpty()) {
echo "No data rows.\n";
return;
}
$rows = $session->toArray();
foreach ($rows as $row) {
print_r($row);
}No matching example found.Try a method name, task, or result.
Was this guide useful?Use GitHub issues for corrections, missing examples, or unclear behavior.
Open an issue