Download the PHP package mnb/mnb-phpexcel without Composer
On this page you can find all versions of the php package mnb/mnb-phpexcel. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package mnb-phpexcel
MNB PHPExcel
MNB PHPExcel is an application-ready PHP Excel engine with a rich small/normal workbook mode plus separate streaming modes for large XLSX import and export. Documentation URL: https://mnbphpexcel.space/
Current development release:
This package keeps the rich workbook reader/writer optimized for small and normal files. Large XLSX files are handled through separate preflight/advisor + streaming import/export layers so applications do not load huge workbooks into PHP arrays.
Unified workbook metadata
The versioned metadata schema reports document/revision/application properties, workbook sheets, hidden content, security, macros, named objects, links, comments, embedded objects, calculations, print settings, validations, pivots and package/container details. Profiles are quick, standard, full, and forensic. XLSX and native XLS provide format-aware collectors plus atomic metadata updates; CSV provides encoding, dialect, structure, statistics, and formula-injection risk analysis while workbook-only sections are explicitly marked not_applicable. See docs/UNIFIED_METADATA.md.
Install
Backward-compatible full package:
Lightweight format packages can be published from the generated release trees:
Format-specific modular entry points avoid loading the legacy all-in-one facade:
See docs/MODULAR_PACKAGES.md for package ownership and release instructions.
v1.7 XLSX encryption and protection APIs
v1.7 adds standards-compatible password-to-open encryption for XLSX files and native workbook/worksheet protection. Both ECMA-376 Agile AES-256/SHA-512 and compatibility-oriented Standard AES-128/SHA-1 containers are supported for reading and writing. Encrypted files work through normal reads, large reads, metadata inspection, upload validation, and integrity validation.
File encryption controls whether the workbook can be opened. Workbook and worksheet protection control editing actions after opening and are not a replacement for encryption. See docs/XLSX_SECURITY_1_7.md.
v1.6 full compatibility APIs
v1.6 removes hard ZIP/XMLReader requirements from functional XLSX, XML, and ODS workflows by adding secure pure-PHP package/XML fallbacks while retaining automatic native-extension streaming when available. It also adds legacy XLS writing through the dedicated XLS package, expanded formulas and custom functions, advanced pivot layouts, transactional PDO queues, persistent PDO schedules, a process runner, authenticated HTTP endpoints, a complete AJAX client, rate limiting, and SMTP/STARTTLS delivery.
For huge XML/XLSX/ODS documents, install native ext-zip and ext-xmlreader to retain true forward-only, bounded-memory streaming. The fallback path prioritizes portability and correctness. See docs/FULL_COMPATIBILITY_1_6.md.
v1.5 full workflow APIs
v1.5 adds a dependency-free formula evaluator for common business formulas, native from-scratch pivot-table generation, multi-file imports, a durable filesystem queue and worker, AJAX upload storage, an API dispatcher, MIME spreadsheet email attachments, and cron-style import/export scheduling.
Native pivot generation is available on WorkbookBuilder::addPivotTable(). Template-driven pivot preservation remains available for highly customized pivots, slicers, and data-model workbooks. See docs/FULL_WORKFLOWS_1_5.md.
v1.4 typed domain import APIs
The database/application packages now provide first-class imports for users, products, orders, inventory, students, attendance, marks, contacts, locations, blog posts, media paths, and categories. Each preset includes canonical columns, common header aliases, validation, defaults, normalization, duplicate keys, template metadata, and cross-field rules.
Generate a validated Excel template from the same preset:
The convenience layer remains configurable: aliases, mappings, rules, defaults, normalizers, transformers, unique keys, duplicate policies, progress callbacks, and row-error callbacks can be overridden. See docs/DOMAIN_IMPORTS_1_4.md.
v1.3 full Excel APIs
The native XLSX module now includes direct cell/range access, complete style metadata, typed rich text, embedded-image extraction, semantic header detection, validated import templates, arbitrary freeze panes, advanced native filters, native conditional formatting, native charts, and native pivot-table generation plus template-driven pivot preservation.
See docs/EXCEL_FULL_CAPABILITIES_1_3.md for complete examples and exact compatibility boundaries.
Required for core package features:
Required for XLSX read/write:
Required only for SQL import/export helpers:
Recommended for better legacy CSV encoding support:
Large XLSX streaming export
Use the large writer when exporting database-sized reports. It streams rows to worksheet XML and uses inline strings, so the full workbook is not kept in memory.
Export from a PDO cursor without fetchAll():
CSV ZIP fallback is available for ultra-large table exports:
Import dashboard helper
Turn a resumable import manifest into a frontend/admin response:
1.2 reader API
- Real line-by-line NDJSON reading.
- Streaming parser for top-level JSON arrays.
- Forward-only XML reading with optional schema mapping.
- Shared in-memory/disk XLSX string provider.
- Source-level column projection.
- One
ReadSessionfor normal and streaming modes. - Immutable
ReaderOptions, typed progress/state objects, and row error policies. - XLSX merged-cell expansion/metadata and formula-plus-cached-result objects.
- Native ODS reading and an optional legacy XLS adapter.
- Instance-scoped custom reader registration.
Main idea
Most PHP applications already use arrays from database queries, APIs, forms, and admin panels. MNB PHPExcel makes those arrays easy to export, import, validate, inspect, and convert.
Core features
Array-first API
MnbExcel::fromArray()MnbExcel::fromWorkbookArray()MnbExcel::read()(auto-detects XLSX/CSV/JSON/XML)MnbExcel::readXlsx()MnbExcel::readCsv()MnbExcel::readXml()MnbExcel::fromJson()MnbExcel::readJson()MnbExcel::fromSql()toArray()toStructuredArray()toStructuredJson()/saveStructuredJson()importToSql()toJson()/saveJson()toXml()/saveXml()
XLSX support
- Create XLSX files from arrays.
- Read XLSX files into arrays.
- Multiple worksheets.
- Sheet selection by index or name.
- Sheet name listing.
- Relationship-based sheet lookup using
workbook.xml.rels. - Shared strings and inline strings.
- Number, text, boolean, blank, error, date, and formula cells.
- Date style detection.
- Excel 1900 and 1904 date systems.
- Hidden sheet/row/column inspection.
- Hidden row and hidden column skip options.
- Corrupted XLSX structure checks.
- Save-time XLSX integrity validation to prevent handing users broken workbooks.
- Formula cached value or formula text read mode.
- Rich text run metadata for shared strings, inline strings, and comments.
- Comments/notes and hyperlinks exposed through
sheetMetadata()and structured outputmetadata. - Programmatic XLSX hyperlink writing through
hyperlink()/hyperlinks(). - Programmatic XLSX legacy note/comment writing through
comment()/comments(). - Environment capability diagnostics through
MnbExcel::environmentCheck(). - XLSX compatibility verification harness through
MnbExcel::verifyXlsxCompatibility(). - Advanced object preservation from an existing XLSX template through
preserveAdvancedObjectsFrom(). - Public XLSX validation API through
MnbExcel::validateXlsx()andMnbExcel::assertValidXlsx(). - Upload validation with actual-size verification, MIME inspection, ZIP path-traversal detection, entry-count/uncompressed-size limits, compression-ratio checks, encrypted-content rejection, and optional macro/external-link rejection.
CSV support
- CSV read/write.
- Dialect presets:
excel,semicolon,excel_tab,unix,pipe. - Custom delimiter, enclosure, escape, and line ending.
- UTF-8 BOM option.
- Advanced encoding auto-detection.
- UTF-8, UTF-8 BOM, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE, Windows-1252, and ISO-8859-1 support.
- Locale-aware number parsing.
- Locale-aware date parsing.
- CSV injection policy modes:
escape,tab_escape,strip,block,none.
JSON and XML conversion
- Convert XLSX/CSV selected sheet rows to JSON.
- Convert XLSX/CSV selected sheet rows to XML.
- Convert JSON files to XLSX/CSV/XML/SQL through the array-first engine.
- Export array workbooks directly as JSON or XML.
- Preserves associative source keys as JSON object/XML field nodes by default (
preserve_associative_rows => falserestores indexed output). - Supports list rows as array/cell nodes.
- Safe XML tag-name normalization.
- XML escaping for special characters such as
&,<,>, quotes, and apostrophes. - JSON options for pretty output, Unicode preservation, slash preservation, and zero-fraction preservation.
- JSON import supports list-of-objects, single object,
{"rows": [...]}, sheet maps, and{"sheets": ...}workbook formats. - Nested JSON objects can be flattened into columns such as
address.city. - Large JSON integers are decoded as strings to avoid precision loss.
JSON to Excel
Simple list-of-objects JSON:
Convert JSON to XLSX:
Workbook-style JSON becomes multiple sheets:
Read JSON to array:
JSON to CSV/XML:
Improved workbook output structure
For normal imports, toArray() returns only row data. For API/debug/import workflows, use toStructuredArray() to get workbook-level output with all sheets.
Workbook output shape:
For selected-sheet-only structure, use toStructuredSheetArray() or pass ['structure' => 'sheet'] to toStructuredArray().
Return workbook structured output as a JSON string without saving:
Return compact JSON for API responses:
Save workbook structured output directly as JSON:
Header options:
Report builder
MnbExcel::report().- Title rows.
- Subtitle/custom title rows.
- Summary rows.
- Footer rows.
- Built-in templates:
simple,business,finance. - Named styles.
- Header styling.
- Column, row, cell, and range styles.
- Currency, percentage, date, datetime, integer, decimal, and text formats.
- Auto-width estimation.
- Freeze panes.
- Auto filter.
- Conditional row styling.
- Workbook metadata.
- Safe file and sheet names.
Import quality tools
- Import preview.
- Required column detection.
- Unexpected column detection.
- Strict column mode.
- Column mapping suggestions.
- Duplicate row detection.
- Original row number preservation.
- Failed rows report.
- Import summary workbook/sheet.
- SQL dry-run before insert.
Validation
Supported rules:
Validation results include simple error messages and detailed metadata:
Formula and cell safety
- Explicit typed cell helpers:
MnbExcel::text()MnbExcel::number()MnbExcel::bool()MnbExcel::date()MnbExcel::formula()MnbExcel::blank()
- Formula policies:
safeblockallow
- Dangerous formula detection for external links, URLs, and risky functions.
- Formula-like text escaping by default.
- Excel 32,767-character cell limit protection.
- Invalid XML/control character handling.
- Long numeric text detection to avoid precision loss.
- Cell safety scanner.
Examples
Array to XLSX
XLSX to array
XLSX metadata: rich text, comments, and hyperlinks
Structured JSON/XML also includes this metadata by default for XLSX reads:
Disable metadata collection in structured output when you only need row/column payloads:
XLSX comments and hyperlinks writer
You can now create clickable hyperlinks and classic Excel notes/comments directly while generating XLSX files:
For multiple sheets, pass the target sheet name:
The writer creates the required worksheet relationships, comments XML part, VML note drawing, and content-type declarations. The saved workbook is still checked by XlsxIntegrityValidator before the path is returned.
Environment diagnostics and XLSX compatibility verification
Check whether the current PHP runtime supports the library features needed by your application:
The alert helper gives a direct warning when ext-zip, ext-xmlreader, or pdo_sqlite are missing. pdo_sqlite is not required for ordinary exports, but it is strongly recommended for very large XLSX imports with huge shared string tables because it enables disk-backed shared-string caching.
Run the compatibility verification harness before release or after changing XLSX internals:
Generated fixture checks currently cover:
Compatibility matrix:
| Source / workflow | Current verification |
|---|---|
| MNB-generated XLSX | Generated fixtures + integrity validator |
| Microsoft Excel files | Supported through optional external fixture paths |
| LibreOffice Calc files | Supported through optional external fixture paths |
| Google Sheets XLSX export | Supported through optional external fixture paths |
| WPS Office XLSX files | Supported through optional external fixture paths |
| UI-level “opens without repair warning” | Must be confirmed manually in the target desktop app |
XLSX integrity validation / corruption prevention
XLSX exports are validated after writing and before the save call returns. If the generated package fails integrity checks, the partial file is deleted and MnbExcelException is thrown instead of returning a corrupted workbook path.
Manual validation is also available for uploaded/generated XLSX files:
The validator checks required XLSX package parts, relationship targets, content type coverage, XML structure, workbook relationship IDs, and worksheet r:id references.
For strict XML parsing during save validation, require ext-xmlreader:
For special/debug workflows only, save-time validation can be disabled:
Preserve advanced XLSX objects while rewriting rows
Use a source workbook as a same-sheet-order template when you need to rewrite row data but keep advanced package parts such as comments, hyperlinks, drawings, legacy notes, tables, VML, embedded media, charts, and pivot/table package parts. Macros are never executed.
This is intended for small/normal files. Large-file streaming and full Excel object editing remain future engine layers.
Numeric accuracy and reader options
Safe numeric conversion is the default. Ordinary integers and decimals become PHP numbers, while values that would overflow an integer or lose significant decimal precision remain exact strings.
For IDs, phone numbers, ISBNs, account numbers, and high-precision decimal text, you can also preserve every XLSX numeric cell as text:
For XLSX writing, numeric cells are serialized with compact high-precision invariant numbers. Long numeric identifiers should still be written as text because Excel itself has numeric precision limits.
Reader auto-detection and fluent row operations
read() now selects the reader from the file extension and signature. An explicit format option can override detection.
Process rows without creating an intermediate worksheet array for CSV and normal XLSX files:
Other convenience operations:
Header positions are explicit:
Duplicate and uneven row widths can be controlled instead of silently losing values:
CSV with encoding and delimiter auto-detection
JSON Lines / NDJSON reading
JSON Lines is detected from content as well as .jsonl / .ndjson suffixes, so renamed upload files still work.
XML reading
XML created by saveXml() can be read back directly:
For custom XML tags, pass matching reader options:
Excel to JSON
Array-first JSON export:
Excel to XML
Array-first XML export:
JSON to Excel
Simple list-of-objects JSON:
Convert JSON to XLSX:
Workbook-style JSON becomes multiple sheets:
Read JSON to array:
JSON to CSV/XML:
Report builder
Validation and failed rows report
Database connection from .env, config file, constants, or PDO
Real applications usually keep database credentials outside the library, for example in .env, config/database.php, framework config, or constants. MNB PHPExcel now accepts all of these without requiring Laravel/Symfony or vlucas/phpdotenv.
Supported .env keys:
You can also use library-specific keys when you do not want to reuse the app default database:
Create a PDO connection from a real application config source:
Constants are also supported, useful for custom apps with db.php bootstrap files:
All SQL helpers still accept an existing PDO, but now they can also accept .env, config path, DSN, or array directly:
For debugging/admin screens:
SQL dry-run
Release readiness check
Local testing
Run syntax checks:
Run smoke tests:
Run all configured tests:
Build and verify isolated modular packages:
The Composer test scripts are cross-platform and work on Windows PowerShell/CMD as well as Unix shells. They use PHP-based runners instead of find, xargs, or shell for loops.
In this environment, XLSX runtime tests require ext-zip and ext-xmlreader. If they are missing, the XLSX smoke test exits safely with a skip message.
Public release checklist
Before Packagist release:
Do not include:
Scope note
MNB PHPExcel has two intentionally separate paths:
- Rich small/normal mode: full workbook arrays, styles, comments, hyperlinks, metadata, reports, validation, JSON/XML/CSV conversion, and XLSX integrity protection.
- Large import mode: preflight/advisor, streaming row reads, chunk callbacks, PDO batch import, failed-row CSV, progress manifests, and checkpoint/resume.
Do not use the normal reader for very large XLSX files. Run MnbExcel::analyzeXlsxForImport() or MnbExcel::recommendImportMethod() first, then use largeRead() / largeImportToSql() when advised.
Structured JSON/XML output without saving
Use toStructuredArray() when you want a PHP array, toStructuredJson() / toStructuredXml() when you want a string for an API response or variable, and saveStructuredJson() / saveStructuredXml() only when you want to save a file.
Error handling and atomic save guard
All writer save paths now use a temp-file-first workflow for safer exports:
Package exceptions expose stable error codes while preserving the original developer message and previous exception internally.
For logs or admin/debug screens:
The error response includes:
Common codes include:
Lightweight XLSX File, Sheet, and Row Information
Use the quick-info APIs when an application needs workbook metadata or row counts before deciding whether to read/import the workbook. These methods inspect the XLSX ZIP package and worksheet XML without converting cell rows into PHP arrays.
Fast sheet information reads workbook relationships and worksheet dimensions only:
For accurate counts, worksheet XML is scanned without hydrating row values:
Use rowCount() for a single number:
Row-count modes:
| Mode | Meaning |
|---|---|
filled |
Rows containing at least one cell; default |
physical |
Physical <row> elements, including empty styled rows |
last_row |
Highest row index referenced by worksheet XML |
declared |
Last row from the worksheet <dimension>; fastest, but may include stale formatting |
The equivalent methods are also available on Mnb\PHPExcel\Format\Xlsx. Native ext-xmlreader is used for true low-memory scanning. The pure-PHP fallback remains functional but may buffer worksheet XML.
Large Excel Preflight and Method Advisor
MNB PHPExcel keeps the existing rich reader/writer for small and normal Excel files. For large imports, use the preflight/advisor layer first so the application does not load a huge workbook into PHP arrays.
The analyzer inspects XLSX package structure with ZIP/XML streaming and reports:
- file size and uncompressed worksheet XML size
- sheet count, row count, column count, and estimated cell count
- shared string table size
- formulas, comments, hyperlinks, merged cells, drawings, charts, pivots, external links, macros, and tables
- Excel sheet-limit risk
- recommended import method and chunk size
Method decision matrix
| Level | Rows / cells | Recommended method |
|---|---|---|
| Tiny | 1-2,000 rows / up to 50k cells | normal_read |
| Small | 2,001-10,000 rows / up to 150k cells | normal_read |
| Normal | 10,001-50,000 rows / up to 500k cells | normal_read_with_warning or stream on low memory |
| Medium | 50,001-150,000 rows / up to 1.5M cells | streaming_chunk_import |
| Large | 150,001-500,000 rows / up to 5M cells | streaming_chunk_import |
| Very large | 500,001-1,048,576 rows / 5M+ cells | cli_queue_recommended |
| Beyond Excel sheet | Above 1,048,576 rows or 16,384 columns | split sheets / CSV ZIP / DB import |
Streaming import for large XLSX
Useful large-read controls:
For shared hosting, prefer small chunks and CLI/queue for very large files. The streaming reader includes memory and time-budget guards, but PHP HTTP timeouts are controlled by the server, so very large imports should run in a CLI worker whenever possible.
Large Excel Database Import Engine
For very large XLSX imports, do not load the workbook into one PHP array. Use the database import engine so rows are streamed, validated in chunks, inserted with PDO batches, and checkpointed for resume.
The $pdo argument may be an existing PDO, .env path, PHP config file path, DSN string, or config array.
The engine provides:
- streaming chunk validation with existing validation rules
- PDO batch insert without collecting all rows
- failed-row CSV export with Excel row number, errors, and row JSON
- JSON progress manifest for admin dashboards and CLI/queue jobs
- checkpoint/resume from the last completed Excel row
- transaction-per-chunk safety for database inserts
- soft time-budget guard so shared hosting jobs can pause before timeout
Useful helper:
Large import stability options
For database imports that may be restarted or repeated, enable idempotent duplicate handling with a database unique key:
Duplicate strategies:
| Strategy | Behavior |
|---|---|
fail |
Normal insert; database duplicate errors stop the import. |
skip |
Uses driver-specific ignore/do-nothing insert where supported. Best for resume-safe idempotent imports. |
update |
Uses upsert where supported. Requires unique_by. |
Streaming reads can preserve numeric values as strings and convert Excel date serials using styles.xml:
Use preserveNumericStrings() for IDs, phone numbers, account numbers, ISBNs, and other values where PHP integer/float conversion can damage precision or leading-zero semantics.
All-sheet large workbook import
Import every sheet without loading the workbook:
You can also pass a table prefix string. For multi-sheet files, table names are generated as prefix_sheetname:
Failed rows are exported in human-readable CSV by default:
Set failed_rows_format => 'json' to use the older compact machine format.
Recommended flow for shared hosting:
- Run
autoImportPlan()first. - Use the advised chunk size.
- Set
time_budget_secondsbelow the server timeout. - Re-run the same import command with
resume => trueuntil status becomescompleted. - Review
failed_rows_csvfor validation failures.
Real application and plugin integration layer
MNB PHPExcel can now be used as an application-level import system, not only as a one-off Excel helper. The core package remains framework-neutral: it does not require Laravel, Symfony, CodeIgniter, or PSR packages.
Application storage paths
Keep import manifests, failed rows, uploads, reports, and temp files outside vendor:
Import profiles
Profiles avoid passing long option arrays in every controller/job:
Profiles may also be loaded from a PHP file:
Import status and resume
Admin dashboards can read manifest state without importing again:
Resume a CLI/queue/cron job from a manifest:
Upload safety validation
Before accepting a user-uploaded spreadsheet:
For XLSX files, the validator checks required package parts, unsafe ZIP paths, archive entry count, expanded size, per-entry size, suspicious compression ratios, encrypted content, macros, and external links when ext-zip is enabled. Limits are configurable; unsafe paths, suspicious archives, and encrypted content are rejected by default.
Event hooks
Supported application events include before_import, before_chunk, after_chunk, on_failed_row, on_import_paused, on_import_completed, and on_import_failed.
Row transformers
Large SQL imports also accept transformers in options/profile config.
Custom validators
Plugins
Framework or application packages can register profiles, validators, transformers, and event listeners:
Optional logger
PSR-3-like logger objects are supported without requiring psr/log as a dependency.
Release-quality proof suite
MNB PHPExcel now includes proof-oriented helpers for benchmarking, compatibility fixtures, integration readiness, and advanced workbook scope transparency.
Benchmark plan and local performance table
Run internal large writer benchmarks:
Use the table template in docs/benchmarks/README.md to publish measured values for MNB PHPExcel, PhpSpreadsheet, OpenSpout, PHP_XLSXWriter, Laravel Excel/FastExcel. Benchmark numbers should be generated on the same machine, same PHP version, same dataset, and same storage disk.
Real Excel fixture compatibility
Recommended real fixture sources:
Run:
Generated XLSX integrity tests are automated. Real application fixtures should still be opened manually in Excel/LibreOffice to confirm there is no repair warning.
MySQL/PostgreSQL integration readiness
Run:
Live MySQL/PostgreSQL checks are skipped unless MNB_EXCEL_TEST_MYSQL_* or MNB_EXCEL_TEST_PGSQL_* environment variables are configured. See docs/DATABASE_INTEGRATION_TESTS.md.
Packagist-ready comparison
See docs/PACKAGIST_COMPARISON.md for the recommended positioning:
Use MNB PHPExcel for real application import/export workflows. Use specialist spreadsheet engines when you need deep workbook editing, a formula calculation engine, or a Laravel-only integration style.
Advanced workbook capability matrix
The matrix covers:
See docs/ADVANCED_WORKBOOK_CAPABILITIES.md.
Framework examples
Examples are included for:
Laravel should be released as a separate adapter package, not inside the core library. See docs/ADAPTER_PACKAGES.md.
All versions of mnb-phpexcel with dependencies
ext-json Version *
ext-openssl Version *
php Version >=8.1