Skip to content
MNB PHPExcelDeveloper Guide
AI

Reading workbooks

Worksheets and Header Rows

Select worksheets reliably and handle title rows, blank rows, and inconsistent headers.

Level
Intermediate
Reading time
10 min
Package
mnb/mnb-phpexcel
Updated
Full packageIndividual XLSX1-based sheets
sheet()hasSheet()sheetIfExists()activeSheet()withHeaderRow()headerAtPhysicalRow()firstNonEmptyRowAsHeader()autoDetectHeader()detectHeader()

Prefer worksheet names for business files#

PHP
$session = MnbExcel::read('monthly-report.xlsx');

if (!$session->hasSheet('Transactions')) {
    throw new RuntimeException('Required worksheet "Transactions" is missing.');
}

$sheet = $session->sheet('Transactions');

// Optional input can fall back to the workbook active sheet.
$optional = $session->sheetIfExists($requestedSheet)
    ?? $session->activeSheet();

Choose the correct header terminology#

MethodMeaning
withHeaderRow(1)Common convenience method for the first header row.
headerAtPhysicalRow(4)Uses the literal worksheet row number, including blank/title rows.
headerAtDataRow(2)Uses the second non-skipped data row.
firstNonEmptyRowAsHeader()Uses the first row containing values.
autoDetectHeader()Scores candidate rows semantically.

Inspect auto-detection before importing#

PHP
$sheet = MnbExcel::read('supplier-upload.xlsx')->sheet(1);
$detection = $sheet->detectHeader();

printf("Detected row: %d\n", $detection->row);
printf("Confidence: %.2f\n", $detection->confidence);

if ($detection->confidence < 0.60) {
    throw new RuntimeException('Header confidence is too low for automatic import.');
}

$rows = $sheet->autoDetectHeader()->rows();

Normalize duplicate or blank header names#

The read session normalizes headers into usable keys. For strict integrations, validate the resulting key set against expected columns before processing records. Continue with sheet selection, empty rows, and counts for active-sheet fallbacks and structured row totals.