From c4301a941d20a360bfdaf4a137d3407477d0f18e Mon Sep 17 00:00:00 2001 From: gouyu-hou Date: Sat, 28 Nov 2026 15:25:37 +0800 Subject: [PATCH] fix(csv): take the header from the first non-blank line A CSV that starts with a blank line - the shape Excel and many exporters produce - lost the entire table: the blank line became the header, so the column width was 0, every cell was rendered as an empty string and the parser reported an empty document. A UTF-8 BOM survived the decode and ended up inside the first header cell instead. Skip the leading blank rows and strip the BOM before the table is built. --- docreader/parser/csv_converter.py | 9 ++++++++- docreader/tests/test_csv_cell_boundaries.py | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/docreader/parser/csv_converter.py b/docreader/parser/csv_converter.py index a13e3b624a6..62bd8e9294b 100644 --- a/docreader/parser/csv_converter.py +++ b/docreader/parser/csv_converter.py @@ -28,7 +28,14 @@ def convert(self, file_stream, stream_info, **kwargs): if stream_info.charset else str(from_bytes(data).best()) ) - rows = list(csv.reader(io.StringIO(content))) + # A BOM survives the decode and would end up inside the first header + # cell; strip it before the table is built. + rows = list(csv.reader(io.StringIO(content.lstrip("\ufeff")))) + # Exported sheets often start with a blank line. Taking that line as the + # header leaves a width of 0, which turns every cell of the table into an + # empty string and drops the whole document. + while rows and not any(cell.strip() for cell in rows[0]): + rows.pop(0) if not rows: return DocumentConverterResult(markdown="") width = len(rows[0]) diff --git a/docreader/tests/test_csv_cell_boundaries.py b/docreader/tests/test_csv_cell_boundaries.py index 680de31ddd8..05e20c191ce 100644 --- a/docreader/tests/test_csv_cell_boundaries.py +++ b/docreader/tests/test_csv_cell_boundaries.py @@ -40,3 +40,21 @@ def test_encoding_and_plain_inputs_keep_their_values(self): Parser().parse_file("plain.csv", "csv", b"A,B\nx,2\n").content, "| A | B |\n| --- | --- |\n| x | 2 |", ) + + def test_leading_blank_line_does_not_eat_the_table(self): + data = b"\r\nname,age\r\nAlice,30\r\n" + for engine in ["", "builtin", "markitdown"]: + with self.subTest(engine=engine): + result = Parser().parse_file("blank.csv", "csv", data, engine) + self.assertEqual( + result.content, "| name | age |\n| --- | --- |\n| Alice | 30 |" + ) + + def test_bom_is_not_part_of_the_first_header_cell(self): + data = "name,age\r\nAlice,30\r\n".encode("utf-8-sig") + for engine in ["", "builtin", "markitdown"]: + with self.subTest(engine=engine): + result = Parser().parse_file("bom.csv", "csv", data, engine) + self.assertEqual( + result.content, "| name | age |\n| --- | --- |\n| Alice | 30 |" + )