Read Excel Percentages and Amounts with Their Formats
When automating Excel report processing or performing document translation, developers often fall into a subtle trap: directly reading cell.value and assumes th
If you automate Excel report processing or document translation, you can fall into a subtle trap: reading cell.value and assuming it is what the user sees. A cell that displays "15%" may store only 0.15. A cell that displays "¥1,234.50" may store only 1234.5. If your code ignores number_format, the downstream system receives raw numbers with no business meaning, which leads to translation errors or wrong calculations.
This guide uses openpyxl to show how to read values and formats together, and how to set acceptance criteria you can trust. It is written for developers and data teams who build ETL jobs, report parsers, or translation pipelines.
How do you read Excel percentages and amounts with their formats? The short answer
Read cell.value for the stored data, read cell.number_format for the display rules, and flag any format your code cannot handle for manual review.
| Your situation | What to do | Why |
|---|---|---|
| A cell shows "15%" or "¥1,234.50" | Read both cell.value and cell.number_format | The stored value may be only 0.15 or 1234.5 |
| The cell value is empty (None) | Return an empty string, whatever the format | Nothing is displayed, so there is nothing to format |
| The format is custom, conditional, or a built-in alias | Return [UNHANDLED] with the original value | Guessing can produce wrong output, so a reviewer should decide |
| You translate a document with Excel tables | Check formulas, identifiers, and citations after translation | Translation must not change these elements |
| Your code expects a percentage but finds text | Flag [TYPE_MISMATCH] and keep the original text | Forced conversion can hide a real data problem |
Why cell.value alone can mislead
Storage and presentation are kept apart
Excel separates the data in a cell from how that data looks. Each cell has two independent properties:
value: the stored data, such as a float, int, or datetime.number_format: a format string that tells the client how to render the value.
openpyxl reflects this separation. It does not convert 0.15 into the string "15%" for you.
The same number can mean different things
Consider the number 1234.5:
- Formatted as
#,##0.00, it represents an amount. - Formatted as
0.00%, it represents a ratio.
In translation, an amount may need its currency symbol kept and its thousands separator converted. A ratio needs the target language's convention for the percent sign checked. Ignoring the format loses this context, including "percentage," "currency unit," and "precision." Understanding this mechanism is essential for writing robust parsing code.
Setting input and output boundaries
To restore the human-readable display value, begin by defining a clear input-output contract.
- Input:
cell.value(which may be None, a number, a date, or text) andcell.number_format(which may be empty,'General', or a complex custom string). - Output: a deterministic string. If the value cannot be processed, return the original value with an explicit marker.
The key boundary conditions are:
- Null value handling: when
valueis None, output an empty string, regardless of the format. - General format: when
number_formatis'General', convert the value using Python's default rules instead of raising an error. - Type mismatch: when the format requires a percentage but the value is text, do not force a conversion. Flag an exception instead.
- Unhandled format: for conditional formats (such as
[Red]), color codes, or rare locale formats, do not guess. Return[UNHANDLED:format_string] original_valuefor human review.
This defensive approach keeps automated workflows stable and makes uncertainties visible to reviewers.
Checking the approach with synthetic data
The Python code below builds sample cells in memory and extracts their display values. It is for educational demonstration only. It has not been run in a production environment, so verify it yourself with openpyxl 3.1.0 or later locked in your environment. The example does not implement a full Excel format parser. It focuses on safe fallbacks for the most common cases.
from openpyxl import Workbook
def get_display_value(cell):
"""
根据 number_format 安全生成显示字符串。
输入: openpyxl Cell 对象
输出: 格式化后的字符串,或带标记的原始值
"""
val = cell.value
fmt = cell.number_format or 'General'
# 边界1: 空值直接返回
if val is None:
return ''
# 边界2: General 或空格式按默认处理
if fmt == 'General':
return str(val)
# 高频场景: 百分比 (假设存储值为小数)
if fmt == '0.00%':
try:
return f'{float(val) * 100:.2f}%'
except (ValueError, TypeError):
return f'[TYPE_MISMATCH:{fmt}] {val}'
# 高频场景: 人民币金额
if fmt.startswith('¥') and '#,##0.00' in fmt:
try:
return f'¥{float(val):,.2f}'
except (ValueError, TypeError):
return f'[TYPE_MISMATCH:{fmt}] {val}'
# 兜底: 未覆盖格式,保留原始值并标记
return f'[UNHANDLED:{fmt}] {val}'
# === 构造合成测试数据 ===
wb = Workbook()
ws = wb.active
# 准备测试用例
ws['A1'] = 0.15
ws['A1'].number_format = '0.00%'
ws['B1'] = 1234.5
ws['B1'].number_format = '¥#,##0.00'
ws['C1'] = 0.999
# C1 保持默认 General 格式
# === 验证预期输出 ===
assert get_display_value(ws['A1']) == '15.00%', "百分比格式化失败"
assert get_display_value(ws['B1']) == '¥1,234.50', "货币格式化失败"
assert get_display_value(ws['C1']) == '0.999', "General格式处理失败"
print("所有断言通过,逻辑符合预期。")
The example wraps the format-mapping logic in a pure function, which makes unit testing easier. In production, move the format whitelist into a configuration file, and set up monitoring and alerts for [UNHANDLED] tags.
Acceptance criteria and manual review
Scripts cannot cover every Excel format variant. The table below sets the code-level acceptance baseline and lists the cases that need manual review. It applies only to validating format-extraction logic. It does not measure the quality of an end-to-end document conversion.
| Observation | Automated decision | Manual review needed? |
|---|---|---|
number_format='0.00%' and value=0.15 | output '15.00%' | No |
number_format contains a currency symbol but value is text | keep the original text, marked [TYPE_MISMATCH] | Yes |
number_format is a custom Chinese format such as '元#,##0.00' | return [UNHANDLED] and the original value | Yes |
value is a datetime but number_format='General' | output an ISO-format string | No |
number_format is an empty string or None | treat as 'General' | No |
format has conditional expressions such as [>100]"高";[<0]"负" | return [UNHANDLED] and the original value | Yes |
uses a built-in style alias such as 'Percent' instead of a specific format string | return [UNHANDLED] and the original value | Yes |
Please note: openpyxl supports built-in named styles only in a limited way. Localised names, such as "Percentage" in the Chinese version of Excel, may not be recognised. In those cases, check the source file's actual display by hand.
Applying the checklist to document translation
Before translating a document with tables, decide which elements are text, which are formulas, and which are business codes. Then translate the tables. After translation, check two things: that the content has been correctly rendered into the target language, and that formulas, identifiers, and citation relationships have stayed unchanged.
OmniDoc translates PDF, Word, PowerPoint and Excel files: scanned pages are recognized first, table cells are translated one by one so tables keep their rows and columns, and a PDF comes back as both a bilingual and a translation-only file. Paid translation adds a glossary and context translation.
Further reading
🎯 Which approach fits you?
If you migrate data or run ETL cleansing
Read the value and the format together, and keep the format as context for downstream steps. Do not rely on value alone.
If you translate spreadsheets or bilingual documents
Check the target language's convention for percent signs and currency symbols. Confirm that formulas and identifiers survive translation unchanged.
If your reports use custom or Chinese number formats
Expect [UNHANDLED] results and send them to a reviewer. Add the formats you see most often to your configuration whitelist over time.
❓ FAQ
1. Why does cell.value return 0.15 when the cell shows 15%?
Excel stores the number separately from its display format. openpyxl returns the stored value and does not apply the 0.00% format for you.
2. What should my code return for an empty cell?
Return an empty string, whatever the number format is. There is no displayed content to format.
3. What happens when a format is too complex to handle?
Return [UNHANDLED:format_string] with the original value, and send the case to manual review. Do not guess the output.
4. Can I rely on the script alone for production files?
No. Test the script with synthetic samples first, then check real files, keep original copies, and verify results against the acceptance criteria in this guide.
📝 Summary
Reading cell.value alone can lose the meaning a number has on screen, so always read the format alongside it. Use explicit boundaries and [UNHANDLED] markers for uncertain cases, and keep a manual review step for them. For translation projects, use the same checklist to confirm that the translated content is correct and that formulas and identifiers are intact.
Try it now: upload a document and get it translated with the layout intact


