PHP code example of mnb / mnb-phpexcel

1. Go to this page and download the library: Download mnb/mnb-phpexcel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mnb / mnb-phpexcel example snippets


$report = MnbExcel::metaInfo('report.xlsx', ['profile' => 'full']);

MnbExcel::updateMetaInfo('report.xlsx', 'report-updated.xlsx', [
    'document' => ['title' => 'Annual Report'],
    'custom_properties' => ['Project ID' => 'PRJ-1001'],
]);

MnbExcel::removePersonalInfo('report-updated.xlsx', 'report-clean.xlsx');

use Mnb\PHPExcel\Format\Xlsx;
use Mnb\PHPExcel\Reader\Options\ReaderOptions;

$options = ReaderOptions::defaults()
    ->withRange(2, 50000, 'A', 'F')
    ->withMode('streaming');

foreach (Xlsx::read('orders.xlsx', $options)->rows() as $row) {
    // process one row
}

use Mnb\PHPExcel\Format\Xlsx;
use Mnb\PHPExcel\MnbExcel;
use Mnb\PHPExcel\Reader\Options\ReaderOptions;

// Encrypt an existing XLSX. Agile AES-256 is the secure default.
MnbExcel::encryptXlsx('report.xlsx', 'report-secure.xlsx', 'S3cret!');

// Standard AES-128 mode maximizes compatibility with older/free viewers.
MnbExcel::encryptXlsx('report.xlsx', 'report-compatible.xlsx', 'S3cret!', [
    'mode' => 'standard',
]);

// Read through the normal API.
$options = ReaderOptions::defaults()->withPassword('S3cret!');
$rows = Xlsx::read('report-secure.xlsx', $options)->sheet('Report')->toArray();

// Stream an encrypted workbook through the large-file API.
MnbExcel::largeRead('report-secure.xlsx', ['password' => 'S3cret!'])
    ->withHeader()
    ->chunk(1000, function (array $rows): void {
        // import rows
    });

// Encrypt the final file and protect workbook structure and worksheets.
MnbExcel::report($rows)
    ->passwordProtectOutput('S3cret!', [
        'encryption_options' => ['mode' => 'agile'],
        'protect_workbook' => true,
        'protect_sheets' => true,
    ])
    ->save('protected-report.xlsx');

use Mnb\PHPExcel\MnbExcel;
use Mnb\PHPExcel\Format\Xls;

// Native or fallback XLSX/XML/ODS operation is selected automatically.
$rows = MnbExcel::read('orders.xlsx')->sheet('Orders')->toArray();

// The XLS split package installs its BIFF8 compatibility engine.
Xls::write($rows, 'orders.xls');

// Multi-host queue and schedule storage.
$queue = MnbExcel::pdoQueue($pdo);
$scheduler = MnbExcel::pdoScheduler($pdo);

// Full backend HTTP endpoint and SMTP delivery are framework-neutral.
$response = MnbExcel::apiHttp($options, $pdo); // handles PHP superglobals

use Mnb\PHPExcel\MnbExcel;

MnbExcel::importDomainFiles('products', $files, $pdo, 'products', [
    'import_options' => ['duplicate_strategy' => 'update', 'unique_by' => ['sku']],
]);

$queue = MnbExcel::queue(__DIR__ . '/storage/queue');
$queue->enqueueDomainImport('products', 'products.xlsx', $databaseConfig, 'products');
MnbExcel::workQueue(__DIR__ . '/storage/queue');

MnbExcel::scheduler(__DIR__ . '/storage/schedule.json')
    ->scheduleExport('daily-report', '0 6 * * *', $rows, __DIR__ . '/reports/daily.xlsx');

use Mnb\PHPExcel\MnbExcel;

$preview = MnbExcel::previewDomainImport('products', 'products.xlsx', [
    'sheet' => 'Products',
    'limit' => 25,
]);

$result = MnbExcel::importProducts('products.xlsx', $pdo, 'products', [
    'duplicate_strategy' => 'update',
    'unique_by' => ['sku'],
    'batch_size' => 1000,
    'failed_rows_csv' => __DIR__ . '/failed-products.csv',
]);

MnbExcel::domainImportTemplate('products')->save('product-import-template.xlsx');

$sheet = Xlsx::read('report.xlsx')->sheet('Sales');
$details = $sheet->cellDetails('D12');
$images = $sheet->extractImages(__DIR__ . '/images');

$rows = Xlsx::read('upload.xlsx')->autoDetectHeader()->toArray();

use Mnb\PHPExcel\MnbExcel;

MnbExcel::largeExport($rowGenerator)
    ->withHeader()
    ->sheetName('Orders')
    ->formatColumn('amount', 'currency')
    ->autoSplitSheets(true)
    ->progress(function (array $state) {
        // update CLI/admin progress
    }, 5000)
    ->save('orders.xlsx');

MnbExcel::largeExportFromSql(__DIR__ . '/.env', 'SELECT id, name, amount FROM orders')
    ->formatColumn('amount', 'decimal')
    ->save('orders.xlsx');

MnbExcel::largeExport($rowGenerator)
    ->withHeader()
    ->csvRowsPerFile(500000)
    ->saveCsvZip('orders-csv-parts.zip');

$response = MnbExcel::importDashboard($manifestPath, [
    'download_base_url' => '/admin/imports/downloads',
]);

// status, progress percent, failed-row download info, resume action, safe messages

$session = MnbExcel::read('orders.xlsx')
    ->range(2, 100000, 'A', 'H')
    ->projectColumns(['order_id', 'amount'])
    ->streaming()
    ->onRowError('collect')
    ->onProgress($progressCallback, 1000);

foreach ($session->chunks(1000) as $chunk) {
    // Same API for normal and low-memory reads.
}

$errors = $session->rowErrors();

use Mnb\PHPExcel\MnbExcel;

MnbExcel::fromArray($rows)->save('students.xlsx');
$rows = MnbExcel::read('students.xlsx')->toArray();

MnbExcel::fromJson('students.json')
    ->textColumns(['student_id'])
    ->autoWidth()
    ->freezeHeader()
    ->autoFilter()
    ->save('students.xlsx');

MnbExcel::fromJson('school.json')
    ->save('school.xlsx');

$rows = MnbExcel::readJson('students.json')
    ->toArray(['header_row' => true]);

MnbExcel::fromJson('students.json')->save('students.csv');
MnbExcel::fromJson('students.json')->saveXml('students.xml', [
    'root' => 'students',
    'row' => 'student',
]);

$structured = MnbExcel::read('Heilberufe.xlsx')
    ->toStructuredArray([
        'header_row' => true,
        'skip_empty_rows' => true,
        '

[
    'status' => 'ok',
    'source' => [
        'file' => 'Heilberufe.xlsx',
        'format' => 'xlsx',
        'size_bytes' => 9150,
    ],
    'sheets' => [
        0 => [
            'index' => 1,
            'sheetname' => 'Worksheet',
            'name' => 'Worksheet',
            'state' => 'visible',
            'dimension' => 'A1:F27',
            'headers' => ['author_name', 'email', 'title', 'affiliation', 'article_type', 'link'],
            'columns' => [
                [
                    'index' => 1,
                    'letter' => 'A',
                    'header' => 'author_name',
                    'original_header' => 'author_name',
                    'key' => 'author_name',
                    'renamed' => false,
                ],
            ],
            'rows' => [
                [
                    'index' => 0,
                    'row_number' => 2,
                    'values' => [
                        'author_name' => 'Peter Heinz',
                        'email' => '[email protected]',
                    ],
                ],
            ],
            'summary' => [
                'source_rows' => 27,
                'processed_rows' => 27,
                'data_rows' => 26,
                'columns' => 6,
                'header_row_number' => 1,
            ],
            'warnings' => [],
            'errors' => [],
        ],
    ],
    'summary' => [
        'sheet_count' => 1,
        'source_rows' => 27,
        'processed_rows' => 27,
        'data_rows' => 26,
        'columns_total' => 6,
        'skipped_empty_rows' => 0,
    ],
    'warnings' => [],
    'errors' => [],
]

$sheetOnly = MnbExcel::read('Heilberufe.xlsx')
    ->sheet('Worksheet')
    ->toStructuredSheetArray([
        'header_row' => true,
    ]);

$json = MnbExcel::read('Heilberufe.xlsx')
    ->toStructuredJson([
        'header_row' => true,
        'rename_headers' => ['affilication' => 'affiliation'],
    ]);

// assign to variable, print, return from controller, or send as API response
echo $json;

header('Content-Type: application/json; charset=UTF-8');

echo MnbExcel::read('Heilberufe.xlsx')
    ->toStructuredJson([
        'header_row' => true,
        'skip_empty_rows' => true,
    ], [
        'pretty' => false,
        'trailing_newline' => false,
    ]);

exit;

MnbExcel::read('Heilberufe.xlsx')
    ->saveStructuredJson('heilberufe-structured.json', [
        'header_row' => true,
        'rename_headers' => ['affilication' => 'affiliation'],
    ]);

'header_case' => 'snake',      // default: Author Name -> author_name
'header_case' => 'preserve',   // keep original header text
'header_case' => 'camel',      // Author Name -> authorName
'rename_headers' => [
    'affilication' => 'affiliation',
]

[
    'row' => 7,
    'column' => 'email',
    'value' => 'wrong-email',
    'rule' => 'email',
    'message' => 'email must be a valid email.',
]

use Mnb\PHPExcel\MnbExcel;

$rows = [
    ['name' => 'Ravi', 'email' => '[email protected]', 'phone' => '0987654321'],
    ['name' => 'Sita', 'email' => '[email protected]', 'phone' => '0912345678'],
];

MnbExcel::fromArray($rows)
    ->withHeader()
    ->textColumns(['phone'])
    ->autoWidth()
    ->freezeHeader()
    ->autoFilter()
    ->save('students.xlsx');

$rows = MnbExcel::read('students.xlsx')
    ->sheet('Students')
    ->toArray([
        'header_row' => true,
        'skip_empty_rows' => true,
        'preserve_original_row_numbers' => true,
        '

$metadata = MnbExcel::read('source.xlsx')
    ->sheet('Students')
    ->sheetMetadata();

$richTextRuns = $metadata['rich_text'];
$comments = $metadata['comments'];
$hyperlinks = $metadata['hyperlinks'];

$json = MnbExcel::read('source.xlsx')->toStructuredJson([
    'header_row' => true,
]);

$structured = MnbExcel::read('source.xlsx')->toStructuredArray([
    'header_row' => true,
    '

MnbExcel::fromArray($rows)
    ->withHeader()
    ->hyperlink('B2', 'https://example.com', 'Open website', [
        'tooltip' => 'Open external reference',
    ])
    ->comment('C2', 'MNB PHPExcel', 'Please verify this value before sharing.')
    ->save('annotated-report.xlsx');

MnbExcel::fromWorkbookArray([
    'Students' => $studentRows,
    'Summary' => $summaryRows,
])->withHeader()
    ->hyperlink('B2', 'https://example.com/students', 'Students source', ['sheet' => 'Students'])
    ->comment('A2', 'Reviewer', 'Summary checked.', ['sheet' => 'Summary'])
    ->save('school-report.xlsx');

$environment = MnbExcel::environmentCheck();
$alert = MnbExcel::environmentAlert();

if (!$alert['ready']) {
    echo $alert['message'];
    // Example missing 

$report = MnbExcel::verifyXlsxCompatibility([
    // Optional real-world fixtures exported from Excel, LibreOffice, Google Sheets, or WPS Office.
    __DIR__ . '/fixtures/excel-comments-hyperlinks.xlsx',
    __DIR__ . '/fixtures/libreoffice-styles-formulas.xlsx',
    __DIR__ . '/fixtures/google-sheets-export.xlsx',
]);

MnbExcel::fromArray($rows)
    ->withHeader()
    ->save('safe-report.xlsx'); // validated automatically for XLSX output

$result = MnbExcel::validateXlsx('safe-report.xlsx');

if (!$result['valid']) {
    print_r($result['errors']);
}

MnbExcel::assertValidXlsx('safe-report.xlsx'); // throws on failure

MnbExcel::fromArray($rows)
    ->withHeader()
    ->strictXlsxIntegrityValidation()
    ->save('strict-safe-report.xlsx');

MnbExcel::fromArray($rows)
    ->skipXlsxIntegrityValidation()
    ->save('debug-output.xlsx');

MnbExcel::fromArray($newRows)
    ->withHeader()
    ->preserveAdvancedObjectsFrom('source-template.xlsx')
    ->save('updated.xlsx');

$rows = MnbExcel::readCsv('payments.csv', [
    'integer_columns' => ['account_id', 'quantity'],
    'number_columns' => ['amount'],
    'big_integer_mode' => 'string',       // string|float|error
    'numeric_precision' => 'safe',        // safe|native|string
    'max_safe_decimal_digits' => 15,
    'invalid_cast' => 'error',            // preserve|null|error
])->withHeaderRow()->toArray();

$rows = MnbExcel::read('input.xlsx')->toArray([
    'preserve_numeric_strings' => true,
]);

MnbExcel::largeRead('large.xlsx')
    ->withHeader()
    ->preserveNumericStrings()
    ->chunk(1000, function (array $rows): void {
        // Numeric cells are delivered as strings.
    });

$rows = MnbExcel::read('students.csv', [
    'delimiter' => 'auto',
])
    ->withHeaderRow()
    ->skip(10)
    ->limit(100)
    ->selectColumns(['student_id', 'name', 'email'])
    ->toArray();

MnbExcel::read('students.xlsx')
    ->sheet('Students')
    ->withHeaderRow()
    ->chunk(500, function (array $rows, array $state): void {
        // Save or validate this chunk.
    });

$first = MnbExcel::read('students.csv')->withHeaderRow()->first();
$count = MnbExcel::read('students.csv')->withHeaderRow()->countRows();

MnbExcel::read('students.csv')->withHeaderRow()->eachRow(
    function (array $row, int $index): bool {
        return true; // return false to stop
    }
);

// Second normalized non-empty data row. withHeaderRow(2) is the same.
$rows = MnbExcel::readCsv('report.csv')->headerAtDataRow(2)->toArray();

// Exact third physical row in the source file, including leading blank/title rows.
$rows = MnbExcel::readCsv('report.csv')->headerAtPhysicalRow(3)->toArray();

// Ignore leading blank rows and use the first non-empty row.
$rows = MnbExcel::readCsv('report.csv')->firstNonEmptyRowAsHeader()->toArray();

$rows = MnbExcel::readCsv('users.csv', [
    'duplicate_headers' => 'rename', // rename|error
    'extra_columns' => 'collect',    // ignore|error|generate|collect
    'extra_columns_key' => '_extra',
    'missing_columns' => 'error',    // null|error
])->withHeaderRow()->toArray();

$rows = MnbExcel::readCsv('legacy-users.csv', [
    'encoding' => 'auto',
    'delimiter' => 'auto',
    'trim_values' => true,
    'strict_column_count' => true,
])->withHeaderRow()->toArray();

$rows = MnbExcel::read('events.data')
    ->withHeaderRow()
    ->toArray();

// Force a document mode when ithHeaderRow()->toArray();

$rows = MnbExcel::readXml('students.xml')
    ->withHeaderRow()
    ->toArray();

$rows = MnbExcel::readXml('students.xml', [
    'row_tag' => 'student',
    'sheet_tag' => 'worksheet',
])->withHeaderRow()->toArray();

MnbExcel::read('students.xlsx')
    ->sheet('Students')
    ->saveJson('students.json', [
        'header_row' => true,
        'skip_empty_rows' => true,
    ]);

MnbExcel::fromArray($rows)
    ->saveJson('students.json', ['mode' => 'rows']);

// Presentation rows can be omitted explicitly:
MnbExcel::fromArray($rows)
    ->withHeader()
    ->saveJson('students.json', ['data_only' => true]);

MnbExcel::read('students.xlsx')
    ->sheet('Students')
    ->saveXml('students.xml', [
        'header_row' => true,
        'skip_empty_rows' => true,
    ], [
        'root' => 'students',
        'row' => 'student',
    ]);

MnbExcel::fromArray($rows)
    ->withHeader()
    ->saveXml('students.xml', [
        'root' => 'students',
        'row' => 'student',
    ]);

MnbExcel::fromJson('students.json')
    ->textColumns(['student_id'])
    ->autoWidth()
    ->freezeHeader()
    ->autoFilter()
    ->save('students.xlsx');

MnbExcel::fromJson('school.json')
    ->save('school.xlsx');

$rows = MnbExcel::readJson('students.json')
    ->toArray(['header_row' => true]);

MnbExcel::fromJson('students.json')->save('students.csv');
MnbExcel::fromJson('students.json')->saveXml('students.xml', [
    'root' => 'students',
    'row' => 'student',
]);

MnbExcel::report($rows, 'business')
    ->title('Student Export Report')
    ->columns([
        'name' => 'Student Name',
        'email' => 'Email Address',
        'marks' => 'Marks',
        'status' => 'Status',
        'amount' => 'Amount',
    ])
    ->integerColumns(['marks'])
    ->currencyColumns(['amount'], '₹')
    ->conditionalRowStyle(
        static fn (array $row): bool => ($row['status'] ?? '') === 'fail',
        'mnb.row.danger'
    )
    ->metadata(['creator' => 'MNB PHPExcel'])
    ->autoWidth()
    ->save('student-report.xlsx');

$result = MnbExcel::validateImport($rows, [
    'name' => '' => 'mnb_original_row_number',
]);

MnbExcel::fromFailedRows($result['failed'])
    ->withImportSummarySheet(['total_rows' => count($rows)], $result)
    ->save('failed-rows.xlsx');

$pdo = MnbExcel::pdo(__DIR__ . '/.env');

$pdo = MnbExcel::pdo(__DIR__ . '/config/database.php'); // PHP file returning array

$pdo = MnbExcel::pdo([
    'driver' => 'mysql',
    'host' => '127.0.0.1',
    'database' => 'app',
    'username' => 'root',
    'password' => 'secret',
]);

define('MNB_EXCEL_DB_DSN', 'mysql:host=127.0.0.1;dbname=app;charset=utf8mb4');
define('MNB_EXCEL_DB_USERNAME', 'root');
define('MNB_EXCEL_DB_PASSWORD', 'secret');

$pdo = MnbExcel::pdo();

MnbExcel::fromSql(__DIR__ . '/.env', 'SELECT id, name, email FROM students')
    ->withHeader()
    ->save('students.xlsx');

MnbExcel::largeImportToSql('students-large.xlsx', __DIR__ . '/.env', 'students', [
    'with_header' => true,
    'chunk_size' => 500,
    'batch_size' => 250,
    'resume' => true,
]);

$config = MnbExcel::dbConfig(__DIR__ . '/.env');
$summary = MnbExcel::databaseConfigSummary(['base_path' => dirname(__DIR__)]);

$plan = MnbExcel::read('students.xlsx')
    ->sheet('Students')
    ->dryRunImportToSql($pdo, 'students', [
        'header_row' => true,
        'batch_size' => 500,
    ]);

$report = MnbExcel::releaseReadiness(__DIR__);

$structured = MnbExcel::read($file)->toStructuredArray([
    'header_row' => true,
    'skip_empty_rows' => true,
]);

$json = MnbExcel::read($file)->toStructuredJson([
    'header_row' => true,
], [
    'pretty' => false,
    'trailing_newline' => false,
]);

$xml = MnbExcel::read($file)->toStructuredXml([
    'header_row' => true,
], [
    'root' => 'structured_workbook',
]);

MnbExcel::read($file)->saveStructuredJson('output.json', [
    'header_row' => true,
]);

MnbExcel::read($file)->saveStructuredXml('output.xml', [
    'header_row' => true,
], [
    'root' => 'structured_workbook',
]);

use Mnb\PHPExcel\MnbExcel;
use Mnb\PHPExcel\Support\MnbExcelException;

try {
    MnbExcel::fromArray($rows)
        ->withHeader()
        ->save('report.xlsx');
} catch (MnbExcelException $e) {
    // Safe for frontend/API responses. Does not expose local paths or stack details.
    return MnbExcel::safeError($e);
}

$error = MnbExcel::errorReport($e, true);

use Mnb\PHPExcel\MnbExcel;

$file = MnbExcel::fileInfo('orders.xlsx');

print_r([
    'size_bytes' => $file['size_bytes'],
    'sheet_count' => $file['sheet_count'],
    'sheet_names' => $file['sheet_names'],
    'has_macros' => $file['has_macros'],
    'properties' => $file['properties'],
]);

$sheets = MnbExcel::sheetsInfo('orders.xlsx');

foreach ($sheets as $sheet) {
    printf(
        "%s: dimension %s, declared last row %d\n",
        $sheet['name'],
        $sheet['dimension'] ?? 'unknown',
        $sheet['declared_last_row']
    );
}

$sheet = MnbExcel::sheetInfo('orders.xlsx', 'Orders', [
    'accurate_row_count' => true,
]);

print_r([
    'filled_rows' => $sheet['filled_rows'],
    'physical_rows' => $sheet['physical_rows'],
    'last_row' => $sheet['last_row'],
    'columns' => $sheet['columns'],
    'cells' => $sheet['cells'],
    'scan_mode' => $sheet['scan_mode'],
]);

$filledRows = MnbExcel::rowCount('orders.xlsx', 'Orders');
$physicalRows = MnbExcel::rowCount('orders.xlsx', 'Orders', ['mode' => 'physical']);
$lastUsedRow = MnbExcel::rowCount('orders.xlsx', 'Orders', ['mode' => 'last_row']);
$declaredLastRow = MnbExcel::rowCount('orders.xlsx', 'Orders', ['mode' => 'declared']);

$allSheets = MnbExcel::rowCounts('orders.xlsx');

$plan = MnbExcel::autoImportPlan('students.xlsx', [
    'server' => 'shared',
    'memory_limit' => '256M',
    'max_execution_time' => 30,
]);

print_r($plan['advice']);

$advice = MnbExcel::recommendImportMethod('students.xlsx', [
    'server' => 'vps',
    'memory_limit' => '512M',
    'max_execution_time' => 300,
]);

MnbExcel::largeRead('students.xlsx')
    ->withHeader()
    ->chunk((int) $advice['recommended_chunk_size'], function (array $rows, array $state): void {
        // validate and insert this chunk into a database.
        // Never collect all chunks into one giant array.
    });

MnbExcel::largeRead('students.xlsx')
    ->sheet('Worksheet')
    ->withHeader()
    ->skipRows(0)
    ->limitRows(100000)
    ->onlyColumns(['A', 'B', 'C'])
    ->timeBudgetSeconds(25)
    ->memoryGuardRatio(0.85)
    ->chunk(500, $callback);

$result = MnbExcel::largeImportToSql('students.xlsx', $pdo, 'students', [
    'with_header' => true,
    'chunk_size' => 500,
    'batch_size' => 250,
    'manifest_path' => __DIR__ . '/storage/students-import.json',
    'failed_rows_csv' => __DIR__ . '/storage/students-failed-rows.csv',
    'resume' => true,
    'time_budget_seconds' => 25,
    'rules' => [
        'email' => 'nullable|email',
        'amount' => 'nullable|numeric',
    ],
]);

$manifestPath = MnbExcel::largeImportManifestPath('students.xlsx', 'students');

$result = MnbExcel::largeImportToSql('students.xlsx', $pdo, 'students', [
    'with_header' => true,
    'chunk_size' => 500,
    'batch_size' => 250,
    'resume' => true,
    'idempotent' => true,
    'duplicate_strategy' => 'skip', // fail | skip | update
    'unique_by' => ['id'],
    'failed_rows_format' => 'human',
]);

MnbExcel::largeRead('students.xlsx')
    ->withHeader()
    ->preserveNumericStrings()
    ->convertDates(true, 'Y-m-d')
    ->chunk(1000, $callback);

$result = MnbExcel::largeImportWorkbookToSql('school.xlsx', $pdo, [
    'Students' => 'students',
    'Scores' => 'scores',
], [
    'chunk_size' => 500,
    'batch_size' => 250,
    'resume' => true,
]);

MnbExcel::largeImportWorkbookToSql('school.xlsx', $pdo, 'import');

use Mnb\PHPExcel\MnbExcel;

MnbExcel::storage([
    'base_path' => __DIR__ . '/storage/mnb-phpexcel',
    'temp_path' => __DIR__ . '/storage/mnb-phpexcel/temp',
    'upload_path' => __DIR__ . '/storage/mnb-phpexcel/uploads',
    'manifest_path' => __DIR__ . '/storage/mnb-phpexcel/manifests',
    'failed_rows_path' => __DIR__ . '/storage/mnb-phpexcel/failed-rows',
    'reports_path' => __DIR__ . '/storage/mnb-phpexcel/reports',
]);

MnbExcel::registerImportProfile('student_import', [
    'table' => 'students',
    'with_header' => true,
    'chunk_size' => 500,
    'batch_size' => 250,
    'resume' => true,
    'idempotent' => true,
    'duplicate_strategy' => 'update',
    'unique_by' => ['student_id'],
    'rules' => [
        'email' => 'nullable|email',
        'amount' => 'nullable|numeric',
    ],
    'column_map' => [
        'Student ID' => 'student_id',
        'Email Address' => 'email',
    ],
]);

$result = MnbExcel::profile('student_import')
    ->source($_FILES['excel']['tmp_name'])
    ->run(__DIR__ . '/.env');

MnbExcel::loadImportProfiles(__DIR__ . '/config/excel-imports.php');

$status = MnbExcel::importStatus(__DIR__ . '/storage/imports/students.json');

$result = MnbExcel::resumeImport(
    __DIR__ . '/storage/imports/students.json',
    __DIR__ . '/.env',
    ['time_budget_seconds' => 25]
);

$upload = MnbExcel::validateUpload($_FILES['excel'], [
    'allowed_extensions' => ['xlsx', 'csv'],
    'max_size_mb' => 100,
    'strict_mime' => true,
    'max_zip_entries' => 10000,
    'max_uncompressed_size_mb' => 1024,
    'max_zip_entry_size_mb' => 256,
    'max_compression_ratio' => 200,
    'reject_macros' => true,
    'reject_external_links' => true,
]);

if (!$upload['valid']) {
    // show $upload['errors'] to admin/developer UI
}

MnbExcel::on('after_chunk', function (array $event): void {
    // update progress table, cache, websocket, or admin dashboard
});

MnbExcel::on('on_import_failed', function (array $event): void {
    // log/import alert
});

MnbExcel::transformer('clean_student_row', function (array $row): array {
    $row['email'] = strtolower(trim((string) ($row['email'] ?? '')));
    $row['amount'] = str_replace(',', '', (string) ($row['amount'] ?? ''));
    return $row;
});

MnbExcel::largeRead('students.xlsx')
    ->withHeader()
    ->transform('clean_student_row')
    ->chunk(1000, function (array $rows): void {
        // rows are already cleaned
    });

MnbExcel::validator('valid_student_id', function (mixed $value): bool|string {
    return preg_match('/^STU-[0-9]{5}$/', (string) $value) === 1
        ? true
        : 'student_id must match STU-00000 format.';
});

$result = MnbExcel::validateImport($rows, [
    'student_id' => '

use Mnb\PHPExcel\Plugin\PluginRegistry;

MnbExcel::plugin(function (PluginRegistry $registry): void {
    $registry->importProfile('student_import', [
        'table' => 'students',
        'with_header' => true,
    ]);

    $registry->validator('valid_status', fn ($value) => in_array($value, ['active', 'inactive'], true));

    $registry->transformer('trim_strings', function (array $row): array {
        return array_map(fn ($value) => is_string($value) ? trim($value) : $value, $row);
    });

    $registry->event('after_chunk', function (array $event): void {
        // progress notification
    });
});

MnbExcel::setLogger(function (string $level, string $message, array $context): void {
    error_log(strtoupper($level) . ': ' . $message . ' ' . json_encode($context));
});

$plan = MnbExcel::benchmarkPlan([
    'rows' => [100000, 500000, 1000000],
    'columns' => 10,
]);

$$report = MnbExcel::verifyCompatibilityFixtures(__DIR__ . '/docs/fixtures');

$plan = MnbExcel::databaseIntegrationPlan();
$check = MnbExcel::databaseIntegrationCheck();

$matrix = MnbExcel::advancedWorkbookCapabilities();
bash
php tools/benchmark-large-writer.php --rows=100000 --cols=10 --json
php tools/benchmark-large-writer.php --rows=500000 --cols=10 --json
php tools/benchmark-large-writer.php --rows=1000000 --cols=10 --json
bash
php tools/compatibility-fixture-check.php docs/fixtures
bash
php tools/database-integration-check.php