Skip to content

Preserve literal NA values and blank cells in Excel conversions - #2499

Open
Kunpeng Xie (pentaoa) wants to merge 1 commit into
microsoft:mainfrom
pentaoa:fix/excel-literal-na-values
Open

Kunpeng Xie (pentaoa) wants to merge 1 commit into
microsoft:mainfrom
pentaoa:fix/excel-literal-na-values

Conversation

@pentaoa

Copy link
Copy Markdown

Fixes #2498.

An Excel row containing NA, NULL, and a blank cell currently becomes | NaN | NaN | NaN |. Disable pandas' default NA-token recognition so literal cell text is preserved and blanks remain empty. Apply the same setting to XLS, XLSX, and the legacy showZeroes repair path.

The regression runs real workbooks through MarkItDown.convert_stream, including a small XLS fixture to avoid adding a workbook-writing test dependency. It checks several NA-like strings, blank cells, and integer values against the resulting Markdown table.

Validation:

  • All three new format/path cases fail before the fix and pass afterward.
  • Five focused Excel and legacy-repair tests pass.
  • Eight existing XLS/XLSX file, hinted-stream, unhinted-stream, and file-URI conversion tests pass.
  • Black and git diff --check pass. The full multi-format suite was not run; this change adds no dependencies.

AI assistance: OpenAI Codex was used for investigation, implementation, and local test execution.

@pentaoa

Copy link
Copy Markdown
Author

@microsoft-github-policy-service agree

@Sagytic

Sagytic commented Oct 21, 2026

Copy link
Copy Markdown

Additional XLSX validation for this PR (2026-10-21)

I ran a small independent regression matrix against the following snapshots without modifying either implementation:

Environment: Windows, Python 3.12.14, pandas 3.0.1, openpyxl 3.1.5.

Scenario Base PR head
Korean worksheet name and text, literal NA/NULL/None/n/a/nan tokens, real blank, zero and negative integers Fails expected-value checks Passes
Multiple worksheets, including a completely blank data column Fails expected-value checks Passes
Same multi-sheet input using legacy showZeroes attributes Fails expected-value checks Passes
Non-missing values control Passes Passes

Checks compare the resulting Markdown cell values with the synthetic workbook contents. This adds coverage for non-ASCII sheet names/text and multiple worksheets on the normal and repair paths. Thank you Kunpeng Xie (@pentaoa) for the fix.

Scope: XLSX only. No XLS validation, full test-suite, formula evaluation, performance, or production/customer-data claim. No LLM/API conversion calls were made. Source hashes were recorded for both snapshots.

All fixtures below are synthetic.

Reproducible validation script

Install the normal MarkItDown dependencies plus pandas and openpyxl, then run separately for each checkout:
python markitdown_excel_review.py --source path/to/packages/markitdown/src --output results.json

"""Additional XLSX validation for microsoft/markitdown PR #2499.

Run separately against the PR base and head source directories:
    python markitdown_excel_review.py --source path/to/src --output results.json

Dependencies: MarkItDown's base dependencies, pandas, openpyxl.
--deps optionally adds a directory containing separately installed dependencies.
Only synthetic workbooks are used. No model/API requests are made.
This validates another contributor's fix; it does not implement that fix.
"""
import argparse
import hashlib
import io
import json
from pathlib import Path
import platform
import re
import sys
import zipfile

parser = argparse.ArgumentParser()
parser.add_argument('--source', type=Path, required=True)
parser.add_argument('--deps', type=Path)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()

# Use the host's existing spreadsheet stack before optional extra dependencies.
import pandas
import openpyxl

if args.deps:
    sys.path.insert(0, str(args.deps.resolve()))
sys.path.insert(0, str(args.source.resolve()))
import markitdown
from markitdown import MarkItDown, StreamInfo

SOURCE_ROWS = [
    ['region', 'status', 'note', 'count'],
    ['NA', 'NULL', None, 0],
    ['EU', 'None', '확인', 7],
    ['APAC', 'n/a', '정상', -3],
    ['KR', 'nan', '검토', 5],
]
CONTROL_ROWS = [
    ['region', 'status', 'note', 'count'],
    ['KR', 'active', '검증', 0],
    ['EU', 'inactive', '검토', -2],
]

def workbook_bytes(sheets, legacy=False):
    workbook = openpyxl.Workbook()
    workbook.remove(workbook.active)
    for name, rows in sheets:
        sheet = workbook.create_sheet(name)
        for row in rows:
            sheet.append(row)
    stream = io.BytesIO()
    workbook.save(stream)
    if not legacy:
        stream.seek(0)
        return stream
    modified = io.BytesIO()
    with zipfile.ZipFile(stream) as source:
        with zipfile.ZipFile(modified, 'w', zipfile.ZIP_DEFLATED) as target:
            for entry in source.infolist():
                data = source.read(entry.filename)
                if entry.filename.startswith('xl/worksheets/') and entry.filename.endswith('.xml'):
                    data = data.replace(b'<sheetView ', b'<sheetView showZeroes="0" ', 1)
                target.writestr(entry, data)
    modified.seek(0)
    return modified

def table_rows(markdown):
    result = {}
    active = None
    for line in markdown.splitlines():
        if line.startswith('## '):
            active = line[3:]
            result[active] = []
        elif line.startswith('|'):
            cells = [cell.strip() for cell in line.strip().strip('|').split('|')]
            if all(re.fullmatch(r':?-+:?', cell) for cell in cells):
                continue
            result[active].append(cells)
    return result

cases = [
    ('korean_sheet_literal_tokens', [('검증대상', SOURCE_ROWS)], False),
    ('multiple_sheets_all_blank_column', [
        ('검증대상', SOURCE_ROWS),
        ('추가검증', [['token', 'empty'], ['NA', None], ['NULL', None]]),
    ], False),
    ('legacy_showZeroes_multiple_sheets', [
        ('검증대상', SOURCE_ROWS),
        ('추가검증', [['token', 'empty'], ['NA', None], ['NULL', None]]),
    ], True),
    ('non_missing_values_control', [('Control', CONTROL_ROWS)], False),
]
converter = MarkItDown(enable_plugins=False)
results = []
for name, sheets, legacy in cases:
    expected = {title: [[str(cell) if cell is not None else '' for cell in row] for row in rows] for title, rows in sheets}
    try:
        markdown = converter.convert_stream(
            workbook_bytes(sheets, legacy),
            stream_info=StreamInfo(extension='.xlsx'),
        ).markdown
        actual = table_rows(markdown)
        results.append({'case': name, 'passed': actual == expected, 'expected': expected, 'actual': actual, 'markdown': markdown})
    except Exception as exc:
        results.append({'case': name, 'passed': False, 'error': str(exc)})

source_file = Path(markitdown.__file__).parent / 'converters' / '_xlsx_converter.py'
report = {
    'python': platform.python_version(), 'platform': platform.system(),
    'pandas': pandas.__version__, 'openpyxl': openpyxl.__version__,
    'converter_sha256': hashlib.sha256(source_file.read_bytes()).hexdigest(),
    'pass_count': sum(case['passed'] for case in results),
    'case_count': len(results), 'cases': results,
    'scope': 'Synthetic XLSX only; no XLS, LLM calls, production/customer data, full-suite or performance claim.',
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps({key: value for key, value in report.items() if key != 'cases'}, ensure_ascii=False))
for case in results:
    print(case['case'], 'PASS' if case['passed'] else 'FAIL', case.get('error', ''))

@pentaoa

Copy link
Copy Markdown
Author

Thanks for the independent validation and reproducible script. The Korean worksheet/text and multi-sheet cases, including the showZeroes repair path and completely blank data column, are useful additions to the regression coverage. I appreciate the explicit expected-cell checks and the clear XLSX-only scope.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Excel conversion replaces literal NA/NULL strings and blank cells with NaN

2 participants