Worksheets and Header Rows
Select worksheets reliably and handle title rows, blank rows, and inconsistent headers.
Updated
sheet()hasSheet()sheetIfExists()activeSheet()withHeaderRow()headerAtPhysicalRow()firstNonEmptyRowAsHeader()autoDetectHeader()detectHeader()What you will learn
- Select worksheets strictly, conditionally, or through the workbook active sheet.
- Understand physical-row and data-row header terminology.
- Use semantic header detection when uploads contain title blocks.
Prefer worksheet names for business files#
$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#
| Method | Meaning |
|---|---|
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#
$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.
Was this guide useful?Use GitHub issues for corrections, missing examples, or unclear behavior.
Open an issue