Product number 00123 — why does it only show 123 after export?

Analyze why leading zeros in product codes are lost after Excel export, distinguish between a cell's stored value and its display format, and provide an openpyxl example for writing identifiers as text, an in-memory verification, and a division of labor between automated assertions and manual review.

Key Points of This Article

  • Leading zeros in product codes are usually lost because of a mismatch between the data type and the display format, not because the file is corrupted.
  • When writing, make sure the cell value is a string and set the cell's number_format to "@" (text format).
  • If the input is already an integer such as 123, the leading zeros have been lost upstream, and format settings cannot recover them, so the write should be rejected.
  • Code assertions only verify the structure of the openpyxl in-memory objects; how the content actually appears in Excel still needs manual review.
  • For amounts, quantities, and other numeric values that need calculation, use the custom format "00000" to display zero-padding instead of setting them as text.

When a product number exports as "123", the file is usually not corrupted. The data type and display format simply don't match. If you often generate Excel reports with programs, fields such as numbers and codes that carry leading zeros are the most likely to show this problem. This article explains why leading zeros are lost, gives the method for writing text-type identifiers with openpyxl and the in-memory validation approach, and describes which issues require manual review.

These methods also apply to the translation and organization workflow of multilingual documents. Numbering, formulas, and cross-references in tables may likewise change after translation, so once you've finished reading, you can apply the same checklist items to your own document workflow.

Product IDs lose their leading zeros after export? One-sentence answer

By writing the numbers as text and setting the cell format to Text at the same time, leading zeros are preserved. If the upstream source has already converted the numbers to integers, the leading-zero information is already lost, and formatting can no longer recover it.

Your situationRecommended PracticesCause
Product numbers, codes, and other identifiersWrite the string and set number_format='@'Prevent the client from automatically converting it to a numeric value
Upstream data is already integers 123Pad the string upstream; if padding is not possible, reject the write and log a warning.The leading-zero information has already been lost upstream, and the format cannot be recovered.
Amounts, quantities and other values that need to be calculatedUsing a custom number format, such as "00000"Keep the numeric value, while padding with zeros for display
Long numbers exceeding 15 digitsChange to text formatThe numeric type cannot hold full precision
Batch file has erroredFix with a script, then spot-check manually.Automated validation only covers the data structure level.

Why are values and formats separated?

The key to understanding this issue is to distinguish between "what is seen" and "what is stored". When working with xlsx files in openpyxl, cell.value stores Python objects (str, int, float, datetime, etc.), while cell.number_format is just an instruction string that tells Excel how to render the value.

When you execute ws['A1'] = '00123', openpyxl writes the string "00123" to the XML as-is. However, if number_format is not set, Excel may try to parse it intelligently when opening the file, converting the purely numeric string into a numeric value for display, and the leading zeros will disappear.

The correct approach is to have double insurance:

  • Ensure the value written is of string type;
  • Set number_format to '@' (the Excel text format code).

This is equivalent to telling the application: regardless of the content, treat it as non-computable text, thereby avoiding automatic type conversion on the client side.

Synthetic Example: Correct Writes and Boundary Testing

To verify this mechanism, you can construct a set of synthetic data that includes both normal identifiers and error-prone boundary cases.

  • Normal case: "00123", expected output is the text "00123", left-aligned;
  • Boundary case 1: "00000", expected output is the text "00000", rather than the numeric value 0;
  • Boundary case 2: None or an empty string, expected output is an empty cell, without raising an error;
  • Error case: 123 (integer type). If written directly, the leading-zero information has already been lost upstream and cannot be recovered through formatting.

When processing upstream data, assume the input may be dirty data. The code cannot guess how many leading zeros the integer 123 originally had, so the key to validation is ensuring that the passed-in parameter is already a zero-padded string. If an integer type is detected, a warning should be logged or the write should be rejected, rather than silently converting it to text without the zeros.

Implementing Text-Type Identifier Writing in openpyxl

The following Python example shows how to build a standards-compliant Excel fragment in memory. The code requires an environment with openpyxl >= 3.1.0 installed.

from openpyxl import Workbook
from openpyxl.styles import numbers

def write_product_ids(ws, start_row, ids):
    """
    将产品编号以严格文本格式写入工作表。
    ids: 字符串列表,必须已包含前导零。
    """
    for i, pid in enumerate(ids):
        cell = ws.cell(row=start_row + i, column=1)

        # 边界处理:跳过空值,避免将None转为字符串"None"
        if pid is None or (isinstance(pid, str) and not pid.strip()):
            continue

        # 类型防御:整数输入意味着前导零已在上游丢失
        # 此处抛出异常是为了阻断错误数据流入Excel
        if isinstance(pid, int):
            raise ValueError(f"ID at index {i} is int ({pid}), leading zeros lost upstream.")

        cell.value = str(pid)
        # '@' 是Excel内置的文本格式代码,使用常量避免拼写错误
        cell.number_format = numbers.FORMAT_TEXT

# --- 合成示例执行区(无需外部文件) ---
wb = Workbook()
ws = wb.active

# 准备合成测试数据
test_ids = ["00123", "00000", "A-009", None, ""]

try:
    write_product_ids(ws, 1, test_ids)
except ValueError as e:
    print(f"捕获到上游数据问题: {e}")

# 验收断言(仅针对内存中的Workbook对象)
assert ws['A1'].value == "00123"
assert ws['A1'].number_format == '@'
assert ws['A2'].value == "00000"  # 全零编号保留
assert ws['A3'].value == "A-009"  # 混合字符不受影响
assert ws['A4'].value is None     # 空值未被污染

print("内存对象校验完成,请保存文件后用Excel人工复核显示效果。")

This code does not depend on any external files; all assertions target the Workbook object in memory. Note that passing the assertions only shows that openpyxl's internal data structures are correct. It does not guarantee that Excel will display the content correctly when opened, since that also depends on client-side factors such as Excel's regional settings and AutoCorrect options.

Before processing important documents, keep the original copies, and review them against the scope and acceptance criteria below.

References: openpyxl Styles Documentation

Acceptance Criteria and Boundaries for Manual Review

Automated validation can only cover the data structure level; true acceptance still requires visual inspection. The table below lists common anomalies and their handling decisions, helping to distinguish which are code problems and which are environmental limitations.

Observe the phenomenonPossible causesHandling decisionDoes it require manual review?
The cell displays 123, but the formula bar shows 00123number_format set to General or Numeric formatCheck whether the number_format='@' assignment was missed in the code.No, a code fix is enough.
The cell displays 123, and the formula bar also shows 123.When writing, the value has already been converted to int or float.Trace the upstream data sources and fix the ETL transformation logicYes, the original data needs to be confirmed.
Displays 00123 but right-alignedThe format is text, but Excel misidentifies it as a numeric value.Reapply text formatting, or use the Text to Columns feature to clean the dataYes, batch files need to be fixed with a script.
Long numbers are displayed in scientific notationValues exceeding 15 digits of precision and not set to text formatMust be changed to text format; a numeric type cannot hold it.No, the format configuration is missing.
Some rows are fine, but some rows are losing zeros.Mixed data type writes, no unified preprocessingAdd type checking and conversion inside the write loopYes, the data source quality needs to be investigated.

Scope of inapplicability: This scheme applies only to fields such as identifiers and codes that should not participate in mathematical operations. For values that require calculation, such as amounts and quantities, a text format should not be used. Instead, a custom number format (such as "00000") should be used to display leading zeros while keeping the value numeric in nature. In addition, if Excel has the "Convert text to numbers automatically" option enabled, users may still be prompted to convert the values when opening the file, even if the code writes them correctly. This is client-side behavior and should be noted for the recipient in the delivery instructions.

Use this checklist for document translation

Use this checklist for document translation

First decide which parts are text and which are formulas and business codes, then translate the table. The post-translation check should not only confirm that the Chinese has become the target language, but also confirm that formulas, identifiers, and reference relationships have not been changed.

OmniDoc's document translation supports formats such as PDF, Word, PPT, and Excel. Scanned documents have their text recognized first, tables are translated cell by cell with their rows and columns preserved, and PDFs produce two versions: a bilingual side-by-side version and a translation-only version. Paid translation also lets you upload a glossary and turn on context-aware translation.

📊 Core Comparison

Handling methodApplicable fieldsLeading zerosCan you participate in the calculation?
Text format (string + '@')Product numbers, codes, and other identifiersReservedDoes not participate in mathematical operations
Custom number format (e.g., "00000")Amounts, quantities and other numerical valuesDisplay zero-padding; the numeric value itself stays the same.Okay
Write integers directlyData already converted to integers upstreamLost, beyond recoveryAcceptable, but the numbering semantics are wrong.

🎯 Which approach suits you?

If you need to export identifiers such as product numbers or order numbers

Write them as text, and set number_format='@'; you need to do both.

If your upstream data is already integers

Prefer having the upstream source supply strings; if that can't be arranged, reject the write and log a warning rather than converting silently.

If you need to export amounts or quantities

Use a custom number format to display leading or trailing zeros, rather than converting the values to text format.

If you are handing the file over for someone else to use

In the delivery notes, remind the recipient to watch out for Excel's "automatically convert text to numbers" option, and ask them to spot-check a few rows of data.

❓ Frequently Asked Questions (FAQ)

1. Why does it show only 123 after export?

When writing, the value was treated as a number, so the leading zeros, being meaningless as a mathematical placeholder, were dropped. If the text format is not set, Excel may also automatically infer the data type based on the content when opening the file.

2. Is setting number_format to '@' alone enough?

It is recommended to use double protection: make sure the written value is of string type, and also set number_format to '@'. Doing only one of these may still cause problems.

3. If the code assertions pass, does that mean the Excel display is definitely correct?

Not necessarily. Passing assertions only shows that the openpyxl internal data structures are correct. Client-side factors such as Excel's regional settings and AutoCorrect options can also affect the final display.

4. Can amounts be saved in text format?

They should not be. Amounts and quantities need to take part in calculations, so they should be displayed with leading zeros using a custom number format (such as "00000"), while keeping their numeric nature.

📝 Summary

The core of the product-number zero-dropping problem is that the value type and the display format are not aligned. Write the identifiers as text and set the cell format to text, and use spot checks and manual review to confirm the results.

Try it now: upload a document and start translating right away, with the original layout preserved.

Updated 2026-11-29