Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/two-row-csv-headers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"javascript-excel": patch
---

`detectHeader` (and `importDataset` with `header: 'auto'`) now recognises a two-row header without merges, as CSV files have: a second all-text row whose text cells all sit on columns of typed data joins the header (`Region,Sales,Sales` over `,Q1,Q2` gives `Sales / Q1`, `Sales / Q2`). Two text rows that only fill the table together (`Name,Q1,` over `,Jan,Feb`) are also a two-row header. When the row under the header is all text but only partly fits, it stays data and the confidence is `'low'`.
3 changes: 2 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1180,8 +1180,9 @@ export interface MappedDataset { columns: ImportedColumn[]; data: Array<Record<s
- Each cell counts as **text**, **other** (numbers, booleans, dates, errors) or empty. Text that parses as a number, `TRUE`/`FALSE` or a date under `locale` counts as other, so an all-text CSV row of numbers isn't taken for a header.
- The **table width** is the most common count of filled cells among the scanned rows that have more than one. A cell counts as filled when it has a value or is covered by a horizontal merge.
- **Title rows** are skipped: rows with at most one filled cell when the table is wider than one column, and rows whose one merge spans the table's full width.
- The **header row** is the first remaining row whose cells are all text and which fills at least the table width, provided some column has an "other" value in one of the next five non-empty rows. That gives `confidence: 'high'`. When no row qualifies (an all-text table), it's the first row that is all text and fills the width, with `confidence: 'low'`. If there is none, the first row of the range is used, also `'low'`.
- The **header row** is the first remaining row whose cells are all text and which fills at least the table width, provided some column has an "other" value in one of the next five non-empty rows. That gives `confidence: 'high'`. When no single row qualifies, two adjacent all-text rows that fill the width together, whose lower row passes the stacking test below, are a two-row header, with `confidence: 'high'`. This is a group row over its columns in CSV, such as `Name,Q1,` over `,Jan,Feb`. Otherwise (an all-text table), it's the first row that is all text and fills the width, with `confidence: 'low'`. If there is none, the first row of the range is used, also `'low'`.
- **Multi-row headers:** rows directly above the header row join it while they are all text and either start a merge that reaches down into the next row (a vertically merged "Name") or hold a horizontal merge narrower than the table (a group title such as "Q1"). That is the header react-data-export's header groups write.
- **Stacked header rows without merges** (CSV): the row directly below a single high-confidence header row joins it when it is all text and **every** text cell in it sits on a column whose next five non-empty values below are all "other". A data row can't look like that, because it would make each of those columns mixed. So `Region,Sales,Sales` over `,Q1,Q2` over numbers is a two-row header (flattened to `Sales / Q1`), and so is a units row (`Temp` over `°C`). If that row is all text but only some of its text cells sit on such columns (`Ada,n/a` under `Name,Amount`), it stays data, and the confidence drops to `'low'` so a UI asks the user.

#### Type rules

Expand Down
47 changes: 47 additions & 0 deletions packages/javascript-excel/src/internal/import/header.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,35 @@ export function detectHeader(sheet: Sheet<CellInput>, options: DetectHeaderOptio
return false;
};

// The first LOOKAHEAD non-empty values of column k below rows[idx]: true when
// there is at least one and none is text (the column holds typed data).
const typedBelow = (idx: number, k: number): boolean => {
let seen = 0;
for (let j = idx + 1; j < rows.length && seen < LOOKAHEAD; j++) {
const kind = rows[j]!.kinds[k];
if (kind === 0) continue;
if (kind === 1) return false;
seen++;
}
return seen > 0;
};
// A row stacked directly under a header row (no merges, as in CSV): all
// text, and every non-empty cell sits on a column of typed data. A data row
// can't be that: it would make each of those columns mixed.
const stacksBelow = (idx: number): boolean => {
const y = rows[idx + 1];
if (!y || y.r !== rows[idx]!.r + 1 || !y.allText) return false;
for (let k = 0; k < width; k++) if (y.kinds[k] === 1 && !typedBelow(idx + 1, k)) return false;
return true;
};
// The row under a header looks like data but puts text on a column of typed data.
const textOnTypedBelow = (idx: number): boolean => {
const y = rows[idx + 1];
if (!y || y.r !== rows[idx]!.r + 1 || !y.allText) return false;
for (let k = 0; k < width; k++) if (y.kinds[k] === 1 && typedBelow(idx + 1, k)) return true;
return false;
};

let header: RowInfo | undefined;
let confidence: "high" | "low" = "low";
for (const x of candidates) {
Expand All @@ -149,6 +178,18 @@ export function detectHeader(sheet: Sheet<CellInput>, options: DetectHeaderOptio
break;
}
}
// Two stacked text rows that only fill the table together, such as a group
// row over its columns in CSV ("Name,Q1," over ",Jan,Feb").
if (!header) {
for (const x of candidates) {
const i = rows.indexOf(x);
const y = rows[i + 1];
if (!x.allText || !y || isTitle(y) || !stacksBelow(i)) continue;
let union = 0;
for (let k = 0; k < width; k++) if (x.kinds[k] !== 0 || y.kinds[k] !== 0) union++;
if (union >= tableWidth) return { rows: [x.r, y.r], confidence: "high" };
}
}
if (!header) header = candidates.find((x) => x.allText && x.filled >= tableWidth);
if (!header) return { rows: [top], confidence: "low" };

Expand All @@ -164,6 +205,12 @@ export function detectHeader(sheet: Sheet<CellInput>, options: DetectHeaderOptio
at++;
result.push(rows[at]!.r);
}
// Without merges: a second header row stacked under the first ("Region,Sales,Sales"
// over ",Q1,Q2"). A text row that only partly fits makes the header uncertain.
if (confidence === "high" && result.length === 1) {
if (stacksBelow(at)) result.push(rows[at + 1]!.r);
else if (textOnTypedBelow(at)) confidence = "low";
}
for (let i = rows.indexOf(header) - 1; i >= 0; i--) {
const x = rows[i]!;
if (!x.allText || x.fullWidthMerge || !joinsBelow(x)) break;
Expand Down
2 changes: 2 additions & 0 deletions packages/javascript-excel/test/fixtures/import/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Byte-exact fixtures: line endings (CRLF, CR), BOMs and encodings are what the tests check.
* -text
5 changes: 5 additions & 0 deletions packages/javascript-excel/test/fixtures/import/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Header-detection fixtures

Copied unchanged from react-data-import (`packages/react-data-import/test/fixtures`, generated by its `generate.ts`, commit 24f90d5), so `detectHeader` is checked here on the same files. Only the files about the header are copied. If react-data-import regenerates them, copy them again.

`.gitattributes` turns off line-ending conversion, so the CSV bytes stay as generated.
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
,,
,,
Name,Amount,City
Ada,1,Oslo
Grace,2,Rome
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@



Name,Amount
Ada,1
Grace,2
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Sales report 2024
Exported 2024-02-01

Region,Q1,Q2
North,10,20
South,30,40
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Region,Sales,Sales
,Q1,Q2
North,10,20
South,30,40
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
38 changes: 38 additions & 0 deletions packages/javascript-excel/test/import/fixtures.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Header detection on react-data-import's generated fixtures (copied into
// test/fixtures/import, see the README there).
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { importDataset } from "../../src/import";

const file = (path: string) => new Uint8Array(readFileSync(new URL(`../fixtures/import/${path}`, import.meta.url)));
const formatOf = (path: string) => (path.endsWith(".csv") ? "csv" : "xlsx") as "csv" | "xlsx";

describe("header detection on react-data-import's fixtures", () => {
it.each([
["csv/title-row.csv", [3]],
["csv/blank-rows-before-header.csv", [3]],
["csv/blank-delimited-rows-before-header.csv", [2]],
["xlsx/title-row-merged.xlsx", [2]],
["xlsx/title-rows-unmerged.xlsx", [2]],
["xlsx/blank-rows-before-header.xlsx", [3]],
["xlsx/offset-table.xlsx", [1]],
["xlsx/header-groups.xlsx", [0, 1]],
["xlsx/title-and-header-groups.xlsx", [1, 2]],
])("%s: header rows %j, high confidence (unchanged)", async (path, rows) => {
const r = await importDataset(file(path), { format: formatOf(path) });
expect(r.meta.header).toEqual({ rows, detected: true, confidence: "high" });
});

it("csv/two-header-rows.csv: a two-row header without merges is detected and flattened", async () => {
const r = await importDataset(file("csv/two-header-rows.csv"), { format: "csv" });
expect(r.meta.header).toEqual({ rows: [0, 1], detected: true, confidence: "high" });
expect(r.columns.map((c) => c.key)).toEqual(["Region", "Sales / Q1", "Sales / Q2"]);
expect(r.data.map((row) => ({ ...row }))).toEqual([
{ Region: "North", "Sales / Q1": 10, "Sales / Q2": 20 },
{ Region: "South", "Sales / Q1": 30, "Sales / Q2": 40 },
]);
const explicit = await importDataset(file("csv/two-header-rows.csv"), { format: "csv", header: { rows: 2 } });
expect(explicit.columns).toEqual(r.columns);
expect(explicit.data).toEqual(r.data);
});
});
24 changes: 24 additions & 0 deletions packages/javascript-excel/test/import/header.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,30 @@ describe("detectHeader", () => {
expect(detectHeader(s)).toEqual({ rows: [0, 1], confidence: "high" });
});

it("reads two stacked text rows over typed data as a two-row header (CSV has no merges)", () => {
// Every text cell of the second row sits on a column of numbers, so it can't be a data row.
expect(detectHeader(sheet([["Region", "Sales", "Sales"], ["", "Q1", "Q2"], ["North", "10", "20"], ["South", "30", "40"]]))).toEqual({ rows: [0, 1], confidence: "high" });
// A units row.
expect(detectHeader(sheet([["Temp", "Pressure"], ["°C", "hPa"], ["20", "1013"]]))).toEqual({ rows: [0, 1], confidence: "high" });
});

it("reads a group row over its columns as a two-row header when neither row fills the table", () => {
// toCsv of react-data-export's header groups: "Name,Q1," over ",Jan,Feb".
const s = sheet([["Name", "Q1", ""], ["", "Jan", "Feb"], ["Ada", "1", "2"], ["Bob", "3", "4"]]);
expect(detectHeader(s)).toEqual({ rows: [0, 1], confidence: "high" });
});

it("keeps a first data row with text in text columns as data", () => {
expect(detectHeader(sheet([["Name", "City", "Amount"], ["Bob", "Paris", ""], ["Ada", "Oslo", "10"]]))).toEqual({ rows: [0], confidence: "high" });
});

it("gives low confidence when the row under the header is all text and only partly fits a header", () => {
// "n/a" in a numeric column could be a sub-header or a data value; "Ada" is clearly data.
expect(detectHeader(sheet([["Name", "Amount"], ["Ada", "n/a"], ["Bob", "10"]]))).toEqual({ rows: [0], confidence: "low" });
// A second header row whose first cell sits on a text column.
expect(detectHeader(sheet([["Region", "Sales", "Sales"], ["Area", "Q1", "Q2"], ["North", "10", "20"]]))).toEqual({ rows: [0], confidence: "low" });
});

it("respects range and maxScan", () => {
const s = sheet([["x"], ["y"], ["Name", "Age"], ["Ada", 1]]);
expect(detectHeader(s, { range: "A3:B4" })).toEqual({ rows: [2], confidence: "high" });
Expand Down
Loading