Skip to content

Keep currency labels on currency-formatted xlsx cells - #2614

Open
AP (intertermux-code) wants to merge 2 commits into
microsoft:mainfrom
intertermux-code:fix/53-excel-currency-format
Open

AP (intertermux-code) wants to merge 2 commits into
microsoft:mainfrom
intertermux-code:fix/53-excel-currency-format

Conversation

@intertermux-code

Copy link
Copy Markdown

Fixes #53

When a cell is formatted as currency in Excel, conversion now keeps the currency label instead of dropping it: $5.00 rather than 5.0.

pandas only reads cell values, never number formats, so the converter now also reads each sheet's number formats with openpyxl and renders currency-formatted numeric cells with their symbol or code, honoring the format's decimals and thousands separators ($1,199.00, EUR 100.00, €2,399.00). Cells without a currency format render exactly as before.

Testing: new regression test test_xlsx_currency_number_formats_keep_currency_label plus parametrized test_format_currency ($, €, EUR, locale-prefixed [$€-407], accounting, suffix, negatives; percent/General/quoted-text formats untouched). tests/test_xlsx.py (25 tests) and tests/test_pdf.py (37 tests) green.

pandas only reads cell values, never number formats, so a cell
formatted as currency came out as a bare number ("5.0" instead of
"$5.00"). Read the workbook's number formats with openpyxl and
render currency-formatted numeric cells with their currency symbol
or code, honoring the format's decimals and thousands separators.
Non-currency cells are untouched.

Fixes microsoft#53

@kokokoXUY XU (kokokoXUY) left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: currency labels for xlsx number formats, checked against base and head

I reviewed 2fce07e9e6fb49e6983cf226926b5ec4ee6df20b against its base
4cc9fa17653d695d64fb9eee5b33d4de55ff84e8 (also the current tip of main), using the same
interpreter for both trees (CPython 3.13.12, pandas 3.0.6, openpyxl, PYTHONPATH pointed at each
worktree's packages/markitdown/src). I built fixture workbooks with openpyxl, converted them
through XlsxConverter.convert and through the public MarkItDown().convert_stream entry point,
called _format_currency directly for a 20-case matrix, ran the PR's own tests red/green, and ran
the full packages/markitdown/tests suite on both trees. Thanks for the focused patch and for the
self-reported test results.

What is already correct

  • The new fixture renders exactly as asserted, end to end: $5.00, $1,199.50, EUR 100.00,
    [\u20ac-407] -> \u20ac2,399.00.
  • Row/column mapping between the worksheet and the pandas frame holds in the shapes I tried:
    blank leading row ($5.00 / $1,199.50 land on the right rows), fully blank row in the middle,
    blank rows before the header, trailing blank rows, merged title row, duplicated header labels
    (Cost / Cost.1), and header-only sheets. No misalignment and no mislabelled cell.
  • Non-numeric cells are skipped as intended: text that looks numeric stays 5.0, blank stays
    NaN, bool untouched, 0% and dates untouched, and a sheet without currency formats is
    byte-identical to base.
  • Bracket codes and quoted literals behave: [$\u20a9-412]#,##0 -> \u20a95,
    [$USD-409]#,##0.00 -> USD 5.00, [$GBP-809]#,##0.00 -> \u00a35.00,
    #,##0.00" USD" -> 5.00 USD, #,##0" kg" correctly returns None.
  • The image path is not disturbed by the second load: _XlsxImages.__init__ reads everything it
    needs and closes its own ZipFile before workbook_stream.seek(0) / load_workbook, and
    to_html only replays in-memory bytes, so the stream is free when openpyxl takes it.
    workbook.close() in finally plus read_only=True is the right shape.

The one I would fix before merge: locale-only formats grow a $

[$-407]#,##0.00, [$-409]#,##0.00 and [$-F800]#,##0.00 all carry a locale, not a currency,
yet they render $1,234.50 (base: 1234.5). [$-en-US]#,##0.00 behaves the same way. This is
ordinary Excel output: the bracket is written by every non-US locale, so the patch adds a dollar
sign to numbers that never had one.

Mechanism, at regex level: the first alternative \[\$([^\]-]+)[^\]]*\] requires at least one
non-- character after [$, so it fails on [$-407]; the engine then restarts at the same
position and the single-symbol alternative [$...] matches the literal $ inside the bracket.
Walking _CURRENCY_FORMAT_RE.finditer directly shows the symbol group winning at offset 1, not the
bracket group at offset 0:

fmt '[$-407]#,##0.00'    -> '$1,234.50'    match pos=1 text='$'          groups=(None, None, '$', None)
fmt '[$-en-US]#,##0.00'  -> '$1,234.50'    match pos=1 text='$'          groups=(None, None, '$', None)
fmt '[$-F800]#,##0.00'   -> '$1,234.50'    match pos=1 text='$'          groups=(None, None, '$', None)
fmt '[$USD-409]#,##0.00' -> 'USD 1,234.50' match pos=0 text='[$USD-409]' groups=('USD', None, None, None)

The parametrized test has no locale-only entry (0.00, General, 0%, "Total" #,##0 are all
covered), which is why the hole is invisible in the PR's own run. A fix could reject a symbol that
is immediately preceded by [, or match bare symbols only outside [...]; a regression case such
as (1234.5, "[$-407]#,##0.00", None) would pin it. [$-F800]dddd, mmmm dd, yyyy happens to be
safe only because it contains no #0? placeholder.

Second correctness point: ? optional digit placeholders are rounded away

decimals = re.search(r"\.(0+)", section) counts mandatory zeros only, so "$"#,##0.?? on 5.5
returns $6 (Excel: $5.5). Same shape for #,##0.0?. Counting [0?] in the decimal group and
leaving the value's own digits in place for ? would keep both the optional-digit semantics and
the current behaviour for 0-only formats.

The whole column changes rendering, not only the labelled cells

dataframe[name] = dataframe[name].astype(object) (line 117) applies to the entire column, and
pandas then renders object cells with str() instead of its float64 column-consistent formatter.
Measured on a sheet where only B2 carries "$"#,##0.00:

base: | A | 5.000000e+00 |      head: | A | $5.00
      | B | 1.000000e-01 |            | B | 0.1
      | C | 1.234568e+08 |            | C | 123456789.123
      | D | 2.500000e+00 |            | D | 2.5

The three plain cells in that column changed output, while a sibling column with no currency
format anywhere keeps 1.000000e-01; a single table can now show two float renderings. The PR
description says cells without currency formats are unchanged, so either the description or the
implementation needs adjusting. This is close to what #2516 ("a blank cell should not rewrite
the rest of its column") warned about, and it overlaps open #2533 (float rendering), so the
maintainers may want one decision here rather than two.

Smaller fidelity gaps

  • Only the first section is used (split(";")[0]): accounting negatives
    _($* #,##0.00_);_($* (#,##0.00);... render -$42.50 where Excel shows ($42.50), and
    "$"#,##0.00;;"-" renders $0.00 for zero where Excel shows -.
  • Literals are dropped: "Cost: "$#,##0.00 -> $1,234.50 (base 1234.5), i.e. the prefix text
    disappears; #,##0.00" USD" survives only because the literal is the currency itself.
  • Symbol list vs code list: "\u0e3f"#,##0.00 and [$\u0e3f-41E]#,##0.00 stay untouched (THB is
    in _CURRENCY_CODES but the baht sign is not in _CURRENCY_SYMBOLS, and the bracket form is
    how Excel stores it). Same for the naira/peso/colon signs.
  • .xls is unaffected: XlsConverter.convert (line 302) is a separate path, so the feature is
    .xlsx-only. Worth one line in the description if that is intended.
  • _format_currency(None, fmt) raises TypeError: bad operand type for abs(): 'NoneType'. The
    caller guards with isinstance(value, (int, float)), so this is not reachable today, but the
    annotation says value: float.

Housekeeping: the two changed files are not black-clean

With the repo's pinned hook (psf/black rev 23.7.0, no args; packages/markitdown/pyproject.toml
has no [tool.black], so the default 88 columns applies):

base: black --check _xlsx_converter.py test_xlsx.py -> exit 0, "2 files would be left unchanged"
head: black --check _xlsx_converter.py test_xlsx.py -> exit 1, "2 files would be reformatted"
      _xlsx_converter.py:54 (95 chars)  regex string concatenation
      test_xlsx.py:517     (89 chars)  def test_format_currency(...)

.pre-commit-config.yaml is a single black hook and .github/workflows/pre-commit.yml runs
pre-commit run --all-files on pull_request, so this would fail the repo's own check. It did not
run here either: on 2fce07e9 the two workflow runs (pre-commit #2216, tests #2215) are both
completed/action_required, the state a first-time fork contributor sees until a maintainer
approves the run, and the only check-run is license/cla. Running black (or pre-commit) locally
before the next push will clear it.

Cost of the second load

load_workbook(read_only=True) plus a full cell walk is paid on every conversion, including
workbooks whose cells have no currency format at all. Best of two runs, same machine:

50k cells, no number formats      3.384s -> 3.617s
50k cells, 1/3 currency-formatted 3.426s -> 3.711s
200k cells, no number formats    13.166s -> 14.800s

That is +7% to +12% for a feature that is often absent. Not a blocker at these sizes, but if the
maintainers care, the scan can be narrowed (e.g. skip sheets where no cell has a number format
other than General, or read formats from the openpyxl objects pandas already built) - noting
read-only mode still has to walk the sheet XML.

Tests and suite

Red/green with the PR's own test file dropped into the base tree: -k currency ->
base 13 failed, 25 deselected, head 13 passed; the whole test_xlsx.py is 25 tests on base
and 38 on head (the +13 are this PR's). Cases I would add on top of the existing ones:
locale-only format -> None, "$"#,##0.?? on 5.5, an accounting negative, a literal prefix, and
one plain sibling cell in the same column to pin the dtype side effect.

Full suite packages/markitdown/tests (minus test_cu.py, which cannot be collected without the
azure-ai-contentunderstanding extra), identical test set, only PYTHONPATH swapped:

base (source 4cc9fa17): 26 failed, 973 passed, 3 skipped in 256.78s
head (source 2fce07e9): 13 failed, 986 passed, 3 skipped in 242.51s

The FAILED diff is exactly the 13 new currency tests (12 parametrized cases plus
test_xlsx_currency_number_formats_keep_currency_label) and nothing else; the remaining 13 are the
same on both sides and are local environment gaps (test_cli_misc.py 7, test_cli_vectors.py 3,
test_docintel.py 2, test_module_misc.py 1 - GBK console encoding and missing optional extras
such as azure-ai-contentunderstanding/azure-ai-documentintelligence/SpeechRecognition).

Duplicate work worth coordinating

Issue #53 (labels: bug, open for contribution) now has nine open PRs doing this same job,
not counting #2614: #2538 (the largest, 575 additions, 4 review comments, branch
fix/xlsx-currency-literal-placeholder, commits about reviewer blockers and about ignoring literal
digits when placing labels), #2347, #2149, #2005, #1944, #1878, #1325, #1630. On
2026-09-18 @aslamalkarywk7 said in the issue that they were taking it on and opened #2538 the
same day, so there is already an active effort in review. #2516 is open with the opposite concern
about rewriting the rest of a column, and #2533 is the open float-rendering PR that touches the
same to_html decision. The five or six patches differ mainly in fidelity details (literal
placeholders, section handling, dtype strategy), so it may be worth posting the false-positive and
?-placeholder findings on the issue itself so the maintainers can pick one line of attack instead
of reviewing nine near-identical branches.

How this was produced

Fixture/probe scripts and both trees' raw outputs are in
_r216_md2614_probe.py, _r216_md2614_align.py, _r216_md2614_edges.py, _r216_md2614_mech.py,
_r216_md2614_chart.py next to the worktrees, with _r216_md2614_{base,head}.txt,
_r216_md2614_align_{base,head}.txt, _r216_md2614_edges_{base,head}.txt and
_r216_checks.txt holding the raw output. AI tooling was used to write and run these checks; every
number above is reproducible from the commands in those files, and I did not run pre-commit
itself (only black --check with the same version the hook pins), since the hook environment is
not installed here.

[$-407] style tags carry a locale, not a currency, but the bare-symbol
alternative matched the $ inside the brackets and rendered a bogus $.
Only match bare symbols outside [...]. Also count ? placeholders as
decimal slots (5.5 no longer rounds to $6), and ignore digit characters
inside [...] / "..." when deciding symbol placement. Regression tests
for each case.
@intertermux-code

Copy link
Copy Markdown
Author

@microsoft-github-policy-service agree

@kokokoXUY XU (kokokoXUY) left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up review: both issues from my earlier review are fixed

I reviewed the first commit (2fce07e) and raised two problems. Commit 1289e8f addresses both, and I re-ran my probes against it. Summary: the two fixes are correct, the added tests cover the exact regressions, the branch is based on current main, and black is clean now. Two remaining gaps in the same code path are worth a follow-up, but I would not block on them.

What I verified

  1. Locale-only tags no longer produce a bogus $. [$-407]#,##0.00, [$-409]#,##0.00, [$-F800]#,##0.00 and [$-en-US]#,##0.00 now return None, where the previous head returned $1,234.50. Verified at unit level and end-to-end: an .xlsx fixture using those number formats now renders | locale-407 | 1234.5 | instead of the fabricated $1,234.50.

  2. The canonical OOXML currency form still works. [$<symbol>-<locale>] is matched by the first alternative, so the new (?<!\[) lookbehind does not break it: [$$-409] -> $1,234.50, [$USD-409] -> USD 1,234.50, [$EUR-407] -> EUR 1,234.50, [$GBP-809] -> GBP 1,234.50, and the suffix form #,##0.00 [$EUR-407] -> 1,234.50 EUR. A bare symbol that follows a locale tag is also still accepted, because only the character immediately before it is checked: [$-407]$#,##0.00 -> $1,234.50, and the quoted form [$-407]"$"#,##0.00 -> $1,234.50.

  3. The lookbehind fixes three more cases beyond the one in the report. My matrix shows these changing for the better, none of them covered by a new test yet:

    • [$-407]#,##0.00 "EUR" -> 1,234.50 EUR (previous head: $1,234.50)
    • [$-407]#,##0.00 [$USD-409] -> 1,234.50 USD (previous head: $1,234.50)
    • [$-409] alone -> None (previous head: $1234)
    • [$-409]"#0"#,##0 -> None (previous head: $1,234)
  4. ? digit placeholders are honored. "$"#,##0.?? with 5.5 -> $5.5 (was $6), with 5.25 -> $5.25 (was $5), with 5 -> $5; "$"#,##0.0? with 5 -> $5.0; "$"#,##0.? with 5.5 -> $5.5 (was $6). Red/green: running the new test_xlsx.py against the previous head 2fce07e gives exactly 4 failed, 15 passed, 25 deselected - the three locale cases and [5.5 - "$"#,##0.?? - $5.5] - and the new head gives 44 passed for the whole file.

  5. The masking of the placeholder search fixes symbol placement too. "v1.05 "$#,##0.00 used to render 1234.5 $ on the previous head, because the 0 inside the quoted literal was taken as the first digit placeholder. It now renders $1234.5 (prefix), which is the correct side.

  6. No structural regression. Ten .xlsx fixtures (column side effects, negatives/sections, optional decimals, blank rows, quoted text and codes, percent/date/text cells, two sheets, large floats, text/empty cells) convert to markdown that is byte-identical to the previous head except the four rows this commit intends to change. The four alignment fixtures - blank row in the middle, header on row 3, trailing blank row plus blank column, mixed text/currency column - are unchanged, so table shape and row-to-worksheet alignment are intact.

  7. Formatting is fixed. black 23.7.0 --check on _xlsx_converter.py and test_xlsx.py reports 2 files would be left unchanged. The previous head failed it (95-character regex line, 89-character test signature); both are resolved by this commit.

  8. Mergeability. The branch is rebased onto the current main (merge-base == 4cc9fa17), git merge-tree --write-tree main 1289e8f succeeds, and license/cla is now success. The tests and pre-commit workflow runs are still action_required because this is a first-time contributor - someone with write access needs to approve the run before the required checks can report.

Remaining gaps (non-blocking)

A. # decimal slots are still ignored, so fractional values silently round to integers. _xlsx_converter.py:93 only accepts 0 and ? after the decimal point, so a format whose decimal slots are all # leaves max_decimals == 0:

value format current output what Excel shows
5.5 "$"#,##0.## $6 $5.5
1.2345 "$"0.### $1 $1.234
5.25 "$"#,##0.0# $5.2 $5.25
1234.5 "$"#,##0.### $1,234 $1,234.5

This is the same family as the ? bug that was just fixed, and #,##0.## is a common format in real workbooks, so extending the character class (and distinguishing "trim trailing zeros" from "always show" per slot) would be a natural follow-up with new parametrized cases.

B. The masking is only applied to the placeholder search; decimals and grouped still scan the raw section. Dots inside a quoted literal corrupt both, so quoted prefixes that contain a number change the rendering:

value format current output expected
1234.5 "v1.05 "$#,##0.00 $1234.5 $1,234.50
1234.5 "v1.5: "$#,##0.00 $1234.50 $1,234.50
1234.5 "Q1.2 "$#,##0 $1234 $1,234

In the first row the literal's .0 wins the decimals search at _xlsx_converter.py:93; in the others grouped at _xlsx_converter.py:97 is computed from section.split(".")[0], which stops at the literal's dot and therefore misses the ,. Reusing the masked spans from _xlsx_converter.py:82 (for example by scanning a copy of the section with the masked spans blanked out) would fix both with a couple of lines.

C. ? semantics are approximated, which is fine, but worth a comment or a test so the next reader does not treat it as Excel-exact: when the optional slots trim away completely the decimal separator disappears ("$"#,##0.?? with 5 -> $5, Excel keeps the point), and "$"0.0?0 with 5.5 -> $5.50 while Excel shows the mandatory thousandths slot as well. The tests added in this commit only cover the three cases where the approximation matches Excel.

D. Unchanged from my earlier review. The column-wide astype(object) at _xlsx_converter.py:142 still changes how the other cells of a currency column render (5 -> 5.0, 123456789.123 instead of 1.234568e+08), a quoted label prefix is dropped ("Cost: "$#,##0.00 -> $1,234.50), and the Thai baht sign is missing from _CURRENCY_SYMBOLS, so a format built from that sign returns None; the three-letter form works ([$THB-41E]#,##0.00 -> THB 1,234.50, #,##0.00 "THB" -> 1,234.50 THB).

How this was produced

Two local worktrees of this PR (4cc9fa1 base, 1289e8f head) plus the previous head 2fce07e for red/green, Python 3.13, with markitdown imported from each tree via PYTHONPATH. Unit matrix over roughly 60 number formats against _format_currency, ten .xlsx fixtures driven end-to-end through XlsxConverter.convert and the public MarkItDown().convert_stream, pytest packages/markitdown/tests/test_xlsx.py on both heads, black 23.7.0 --check, and git merge-tree. This review was prepared by an AI coding agent; the commands and outputs above are from this machine, not from the PR author.

Verdict

Both issues I raised are resolved, the fix matches the documented [$<symbol>-<locale>] form, and the new tests fail before the change and pass after it. I would merge this. Gap A is the one I would most like to see as a follow-up issue, since it silently changes currency values rather than just their formatting.

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.

Unable to extract currency from excel formatted cells

2 participants