XLSX · Reading
XLSX reading examples.
Package-local, copy-ready examples organized like the classes and methods reference. Open one example at a time, search by method, and jump from the right-side index.
XLSX individual library
Reading examples with copy-ready, production-minded PHP.
Every snippet uses mnb/mnb-phpexcel-xlsx or its declared Core dependency. Each copied snippet includes strict typing, a concise summary, implementation guidance, readable limits, and a safe fixture check.
- 28
- examples
- 78
- documented methods
Xlsx::read()sheet()withHeaderRow()toArray()<?php
declare(strict_types=1);
/*
Summary:
Open an XLSX workbook, select a worksheet, map row one to associative keys, and collect bounded
rows.
Implementation note:
Use toArray() for small and normal worksheets. For an unknown or very large file, inspect or
stream before collecting every row.
*/
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(1)
->toArray([
'skip_empty_rows' => true,
'max_rows' => 5_000,
]);
foreach ($rows as $row) {
$studentId = trim((string) ($row['student_id'] ?? ''));
$name = trim((string) ($row['name'] ?? ''));
if ($studentId === '' && $name === '') {
continue;
}
printf('%s: %s%s', $studentId, $name, PHP_EOL);
}Expected output
S001: Asha Patel
S002: Daniel WongXlsx::read()withOptions()options()normal()streaming()mode()limit()<?php
declare(strict_types=1);
/*
Summary:
Create a read session with typed options, inspect the effective configuration, and switch
between normal and streaming modes.
Implementation note:
withOptions() returns a cloned session configuration. normal(), streaming(), and mode() choose
the execution path without changing the selected workbook or worksheet.
*/
use Mnb\PHPExcel\Format\Xlsx;
use Mnb\PHPExcel\Reader\ReadMode;
use Mnb\PHPExcel\Reader\ReaderOptions;
$workbookPath = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$options = new ReaderOptions([
'skip_empty_rows' => true,
'convert_dates' => true,
'preserve_numeric_strings' => true,
]);
$session = Xlsx::read($workbookPath, $options)
->withOptions(['max_rows' => 25_000]);
print_r($session->options());
$normalRows = $session->normal()->limit(25)->toArray();
$stream = $session->mode(ReadMode::STREAMING)->rows();Xlsx::cell()<?php
declare(strict_types=1);
/*
Summary:
Use the focused static shortcut when the application needs a single cell rather than a reusable
read session.
Implementation note:
The static shortcut is concise for isolated reads. Create one Xlsx::read() session when several
cells, ranges, or metadata values are needed from the same workbook.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/finance-report.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$title = Xlsx::cell(
$workbookPath,
'B2',
sheet: 'Summary',
options: ['convert_dates' => true]
);
echo (string) $title;Expected output
Quarterly revenue summaryXlsx::rangeValues()<?php
declare(strict_types=1);
/*
Summary:
Return a rectangular cell range from one worksheet through the standalone XLSX facade.
Implementation note:
rangeValues() is useful for a small known area. Use range() plus rows() when the selected source
can contain many records.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/finance-report.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$monthlyTotals = Xlsx::rangeValues(
$workbookPath,
'D5:D16',
sheet: 'Summary',
options: ['formula_cells' => 'cached_value']
);
print_r($monthlyTotals);Xlsx::cellDetails()Xlsx::richText()<?php
declare(strict_types=1);
/*
Summary:
Inspect formula, cached value, comments, hyperlinks, number format, and rich-text runs for
selected XLSX cells.
Implementation note:
cellDetails() returns a typed CellSnapshot. richText() returns null when the cell has no
rich-text runs.
*/
use Mnb\PHPExcel\Format\Xlsx;
$path = __DIR__ . '/fixtures/catalog.xlsx';
if (!is_file($path)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $path));
}
$details = Xlsx::cellDetails($path, 'D12', sheet: 'Products');
$richText = Xlsx::richText($path, 'B2', sheet: 'Products');
print_r([
'value' => $details->value,
'formula' => $details->formula,
'cached_value' => $details->cachedValue,
'number_format' => $details->numberFormat,
'comments' => $details->comments,
'hyperlinks' => $details->hyperlinks,
'rich_text' => $richText,
]);Xlsx::images()Xlsx::protection()<?php
declare(strict_types=1);
/*
Summary:
Read drawing metadata and worksheet protection settings without first collecting tabular rows.
Implementation note:
Leave includeBytes disabled for metadata screens. Enable it only when the application truly
needs embedded image bytes in memory.
*/
use Mnb\PHPExcel\Format\Xlsx;
$path = __DIR__ . '/fixtures/catalog.xlsx';
if (!is_file($path)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $path));
}
$images = Xlsx::images($path, sheet: 'Products', includeBytes: false);
$protection = Xlsx::protection($path, sheet: 'Products');
print_r([
'image_count' => count($images),
'images' => $images,
'protection' => $protection,
]);Xlsx::isEncrypted()Xlsx::encryptionMode()Xlsx::read()sheetNames()<?php
declare(strict_types=1);
/*
Summary:
Detect password-to-open encryption and report the Office encryption mode before creating a read
session.
Implementation note:
Keep workbook passwords outside source control and logs. Password-to-open encryption is
different from workbook or worksheet editing protection.
*/
use Mnb\PHPExcel\Format\Xlsx;
$path = __DIR__ . '/fixtures/confidential.xlsx';
if (!is_file($path)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $path));
}
if (Xlsx::isEncrypted($path)) {
printf("Encrypted XLSX mode: %s\n", Xlsx::encryptionMode($path) ?? 'unknown');
$session = Xlsx::read($path, ['password' => getenv('WORKBOOK_PASSWORD')]);
} else {
$session = Xlsx::read($path);
}
print_r($session->sheetNames());Expected output
Encrypted XLSX mode: agile
Array
(
[0] => Summary
[1] => Data
)Xlsx::read()ReadSession::inspect()<?php
declare(strict_types=1);
/*
Summary:
Inspect package status, file size, encryption, worksheet dimensions, warnings, and validation
errors without materializing rows.
Implementation note:
inspect() reads XLSX package structure and worksheet metadata. It does not convert every
worksheet cell into PHP rows.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$inspection = Xlsx::read($workbookPath)->inspect();
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'],
]);sheetNames()sheet()withHeaderRow()withoutHeaderRow()first()<?php
declare(strict_types=1);
/*
Summary:
Discover sheet names first, then select a required worksheet by name or one-based index.
Implementation note:
Named selection is safest when users can reorder worksheets. Numeric worksheet selection is
one-based.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/sales-workbook.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$workbook = Xlsx::read($workbookPath);
$sheetNames = $workbook->sheetNames();
print_r($sheetNames);
$ordersByName = $workbook->sheet('Orders')->withHeaderRow()->toArray();
$firstSheet = $workbook->sheet(1)->withoutHeaderRow()->first();Expected output
Array
(
[0] => Summary
[1] => Orders
[2] => Archive
)activeSheetName()activeSheetIndex()activeSheetInfo()<?php
declare(strict_types=1);
/*
Summary:
Read the workbook active-sheet name, one-based index, and complete active-sheet metadata.
Implementation note:
For XLSX, active-sheet identity follows workbook activeTab metadata when available and otherwise
falls back to the first readable worksheet.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/dashboard.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$workbook = Xlsx::read($workbookPath);
print_r([
'name' => $workbook->activeSheetName(),
'index' => $workbook->activeSheetIndex(),
'info' => $workbook->activeSheetInfo(),
]);Expected output
Array
(
[name] => Dashboard
[index] => 1
[info] => Array (...)
)hasSheet()sheetExists()<?php
declare(strict_types=1);
/*
Summary:
Check a worksheet name or one-based index without selecting it or throwing for a missing
optional sheet.
Implementation note:
hasSheet() and sheetExists() are non-selecting checks. Invalid or absent optional values return
false rather than changing the current session.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/report.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$workbook = Xlsx::read($workbookPath);
var_dump($workbook->hasSheet('Orders'));
var_dump($workbook->sheetExists('Archive'));
var_dump($workbook->hasSheet(1));
var_dump($workbook->sheetExists(0));Expected output
bool(true)
bool(false)
bool(true)
bool(false)sheetIfExists()withHeaderRow()rows()<?php
declare(strict_types=1);
/*
Summary:
Return a selected read session when a sheet exists and null when an optional worksheet is
absent.
Implementation note:
Use sheet() for mandatory worksheets and sheetIfExists() when absence is a valid application
state.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/report.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$workbook = Xlsx::read($workbookPath);
$archive = $workbook->sheetIfExists('Archive');
if ($archive === null) {
echo "Archive worksheet is optional and was not supplied.\n";
} else {
foreach ($archive->withHeaderRow()->rows() as $row) {
print_r($row);
}
}Expected output
Archive worksheet is optional and was not supplied.sheetOrActive()selectSheetOrActive()withHeaderRow()rows()<?php
declare(strict_types=1);
/*
Summary:
Use the active worksheet only when the requested value is null or empty while keeping non-empty
typos strict.
Implementation note:
sheetOrActive() and selectSheetOrActive() fall back only for null or an empty string. A
non-empty unknown name still throws a clear selection exception.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/report.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$requestedSheet = trim((string) ($_GET['sheet'] ?? ''));
$workbook = Xlsx::read($workbookPath);
$session = $workbook->sheetOrActive($requestedSheet)->withHeaderRow(1);
$equivalent = $workbook->selectSheetOrActive($requestedSheet);
foreach ($session->rows() as $row) {
print_r($row);
}activeSheet()useActiveSheet()first()<?php
declare(strict_types=1);
/*
Summary:
Create a read session targeting the workbook active worksheet through either supported fluent
method.
Implementation note:
activeSheet() and useActiveSheet() are equivalent explicit selections. Both return a cloned
session and preserve the original workbook session.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/dashboard.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$workbook = Xlsx::read($workbookPath);
$active = $workbook->activeSheet()->withHeaderRow();
$alsoActive = $workbook->useActiveSheet()->withHeaderRow();
print_r($active->first());
print_r($alsoActive->first());ReadSession::inspect()<?php
declare(strict_types=1);
/*
Summary:
Find one worksheet in inspection metadata and read dimensions, hidden rows and columns, merges,
filters, and drawing flags.
Implementation note:
Declared dimensions can include stale formatting. row_tag_count is a physical XML-row count, not
a normalized business-record count.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$inspection = Xlsx::read($workbookPath)->inspect();
$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'],
]);sheetNames()sheet()withHeaderRow()countRows()<?php
declare(strict_types=1);
/*
Summary:
List worksheets and count normalized data rows for each one without building complete PHP
arrays.
Implementation note:
countRows() follows the current header, range, projection, offset, limit, filter, and empty-row
options and streams yielded records.
*/
use Mnb\PHPExcel\Format\Xlsx;
$path = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($path)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $path));
}
$workbook = Xlsx::read($path);
$counts = [];
foreach ($workbook->sheetNames() as $name) {
$counts[$name] = $workbook->sheet($name)->withHeaderRow()->countRows(['skip_empty_rows' => true]);
}
print_r($counts);Expected output
Array
(
[Orders] => 1248
[Returns] => 37
[Summary] => 12
)detectHeader()autoDetectHeader()toArray()<?php
declare(strict_types=1);
/*
Summary:
Inspect a messy worksheet, report the likely header row and confidence, then apply semantic
header detection.
Implementation note:
Automatic detection is useful for variable exports with title or blank rows. Use a fixed
physical row for stable supplier formats.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/vendor-export.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$session = Xlsx::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',
]);Expected output
Header row: 4 (confidence 0.92)headerAtPhysicalRow()headerAtDataRow()firstNonEmptyRowAsHeader()withHeaderRow()withoutHeaderRow()first()<?php
declare(strict_types=1);
/*
Summary:
Compare physical-row, data-row, first-non-empty, enabled, and disabled header mappings on cloned
read sessions.
Implementation note:
Each header method returns a cloned session, so several strategies can be compared without
reopening the workbook.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/supplier-upload.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$sheet = Xlsx::read($workbookPath)->sheet(1);
$physical = $sheet->headerAtPhysicalRow(4)->first();
$dataRow = $sheet->headerAtDataRow(2)->first();
$firstNonEmpty = $sheet->firstNonEmptyRowAsHeader()->first();
$defaultHeader = $sheet->withHeaderRow()->first();
$raw = $sheet->withoutHeaderRow()->first();
print_r(compact('physical', 'dataRow', 'firstNonEmpty', 'defaultHeader', 'raw'));range()projectColumns()withHeaderRow()selectColumns()skip()limit()toArray()<?php
declare(strict_types=1);
/*
Summary:
Constrain the source range, project worksheet columns before parsing, and select normalized
header keys afterward.
Implementation note:
projectColumns() reduces source parsing work. selectColumns() filters by normalized header names
after header mapping.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/products.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$rows = Xlsx::read($workbookPath)
->sheet('Products')
->range(startRow: 1, endRow: 5_000, startColumn: 'A', endColumn: 'F')
->projectColumns(['A', 'B', 'F'])
->withHeaderRow()
->selectColumns(['sku', 'name', 'price'])
->skip(10)
->limit(100)
->toArray();withOptions()hasRows()isEmpty()assertHasRows()requireRows()toArray()<?php
declare(strict_types=1);
/*
Summary:
Check whether normalized data exists and enforce a required-row contract before terminal
conversion.
Implementation note:
hasRows() and isEmpty() are Boolean checks. assertHasRows() and requireRows() preserve the
fluent session and throw when the current selection yields no data.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$session = Xlsx::read($workbookPath)
->sheet('Orders')
->withHeaderRow(1)
->withOptions(['skip_empty_rows' => true]);
var_dump($session->hasRows());
var_dump($session->isEmpty());
$session->assertHasRows(message: 'Orders worksheet must contain data.');
$session->requireRows(message: 'At least one order is required.');
$rows = $session->toArray();Expected output
bool(true)
bool(false)first()countRows()rowStates()rows()<?php
declare(strict_types=1);
/*
Summary:
Preview the first normalized row, count the selection, inspect row-state metadata, and iterate
records lazily.
Implementation note:
first(), countRows(), rowStates(), and rows() are separate read passes. Use only the passes the
production workflow actually needs.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$session = Xlsx::read($workbookPath)->sheet('Orders')->withHeaderRow();
print_r($session->first());
echo 'Rows: ' . $session->countRows() . PHP_EOL;
foreach ($session->rowStates() as $state) {
if ($state->isEmpty) {
continue;
}
printf("Physical row %d\n", $state->physicalRow);
}
foreach ($session->rows() as $row) {
processOrder($row);
}Expected output
Array
(
[order_id] => SO-1001
[customer] => Acme
)
Rows: 1248streaming()onProgress()onRowError()chunks()chunk()eachRow()rowErrors()<?php
declare(strict_types=1);
/*
Summary:
Process bounded batches, report progress, choose a row-error policy, and inspect normalized row
errors.
Implementation note:
chunks() yields batches, chunk() invokes a callback per batch, and eachRow() invokes a callback
per record. Pick one terminal iteration style for a production pass.
*/
use Mnb\PHPExcel\Format\Xlsx;
use Mnb\PHPExcel\Reader\RowErrorPolicy;
$workbookPath = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$session = Xlsx::read($workbookPath)
->sheet('Orders')
->withHeaderRow()
->streaming()
->onProgress(static function (int $rowsRead): void {
echo "Read {$rowsRead} rows\n";
}, everyRows: 1_000)
->onRowError(RowErrorPolicy::COLLECT);
foreach ($session->chunks(500) as $chunk) {
processOrderBatch($chunk);
}
$session->chunk(500, static function (array $chunk): void {
archiveOrderBatch($chunk);
});
$session->eachRow(static function (array $row): void {
validateOrder($row);
});
print_r($session->rowErrors());Expected output
Read 1000 rows
Read 2000 rows
Read 3000 rowscell()cells()rangeValues()calculatedCell()calculatedRange()<?php
declare(strict_types=1);
/*
Summary:
Reuse one selected worksheet for direct cells, multiple coordinates, rectangular ranges, and
calculated formula values.
Implementation note:
Formula calculation support is format-native and bounded by the documented XLSX formula engine.
Cached values remain useful for unsupported functions.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/finance-report.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$sheet = Xlsx::read($workbookPath)->sheet('Summary');
$title = $sheet->cell('B2');
$values = $sheet->cells(['B2', 'D17', 'F20']);
$monthlyTotals = $sheet->rangeValues('D5:D16');
$calculatedTotal = $sheet->calculatedCell('D17');
$calculatedMonths = $sheet->calculatedRange('D5:D16');
print_r(compact('title', 'values', 'monthlyTotals', 'calculatedTotal', 'calculatedMonths'));cellDetails()cellStyle()rangeStyles()richText()<?php
declare(strict_types=1);
/*
Summary:
Read a typed cell snapshot, one cell style, a range of styles, and rich-text runs from the
selected worksheet.
Implementation note:
Style and rich-text reads are presentation-oriented. Avoid scanning large style ranges when the
application only needs normalized business data.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/catalog.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$sheet = Xlsx::read($workbookPath)->sheet('Products');
$details = $sheet->cellDetails('D12');
$style = $sheet->cellStyle('D12');
$styles = $sheet->rangeStyles('A1:F20');
$richText = $sheet->richText('B2');
print_r([
'details' => $details,
'style' => $style,
'range_styles' => $styles,
'rich_text' => $richText,
]);images()extractImages()<?php
declare(strict_types=1);
/*
Summary:
Inspect worksheet drawing metadata or extract embedded images to a controlled destination
directory.
Implementation note:
Use an application-owned output directory, validate generated paths, and leave overwrite
disabled unless replacement is intentional.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/catalog.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$sheet = Xlsx::read($workbookPath)->sheet('Products');
$images = $sheet->images(includeBytes: false);
$written = $sheet->extractImages(__DIR__ . '/output/product-images', overwrite: false);
print_r(['images' => $images, 'written_files' => $written]);sheetMetadata()protection()<?php
declare(strict_types=1);
/*
Summary:
Read worksheet-level metadata and editing-protection settings from one selected XLSX sheet.
Implementation note:
Worksheet protection guides editing behavior and is not equivalent to password-to-open
encryption.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/report.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$sheet = Xlsx::read($workbookPath)->sheet('Summary');
print_r([
'metadata' => $sheet->sheetMetadata(),
'protection' => $sheet->protection(),
]);toStructuredSheetArray()toStructuredWorkbookArray()toStructuredArray()<?php
declare(strict_types=1);
/*
Summary:
Return structured payloads for the selected sheet, the complete workbook, or an automatically
selected scope.
Implementation note:
Structured terminal methods return native arrays. Read summary, rows, warnings, errors, source,
workbook, and sheet metadata directly from those results.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$workbook = Xlsx::read($workbookPath)->withHeaderRow(1);
$sheetPayload = $workbook->sheet('Orders')->toStructuredSheetArray([
'preserve_original_row_numbers' => true,
]);
$workbookPayload = $workbook->toStructuredWorkbookArray([
'include_sheets' => true,
]);
$automaticPayload = $workbook->toStructuredArray([
'include_workbook' => true,
]);toJson()toXml()toStructuredJson()toStructuredXml()saveJson()saveXml()saveStructuredJson()saveStructuredXml()<?php
declare(strict_types=1);
/*
Summary:
Convert normal or structured read results to JSON/XML strings or save them directly to
application-owned files.
Implementation note:
String converters keep the result in memory. Save helpers are better when the application needs
a file and should write only to validated, application-owned paths.
*/
use Mnb\PHPExcel\Format\Xlsx;
$workbookPath = __DIR__ . '/fixtures/orders.xlsx';
if (!is_file($workbookPath)) {
throw new RuntimeException(sprintf('Workbook not found: %s', $workbookPath));
}
$sheet = Xlsx::read($workbookPath)->sheet('Orders')->withHeaderRow();
$json = $sheet->toJson([], ['pretty' => true]);
$xml = $sheet->toXml([], ['root' => 'orders']);
$structuredJson = $sheet->toStructuredJson();
$structuredXml = $sheet->toStructuredXml();
$sheet->saveJson(__DIR__ . '/output/orders.json');
$sheet->saveXml(__DIR__ . '/output/orders.xml');
$sheet->saveStructuredJson(__DIR__ . '/output/orders-structured.json');
$sheet->saveStructuredXml(__DIR__ . '/output/orders-structured.xml');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