GrepBoard/Manuals
605 manuals ·

Fix a CSV that garbles Korean and drops leading zeros in Excel

·Tested on Claude Sonnet 5.5 · 2026-10·Test scope ↓·6 steps

Fix garbled text and dropped leading zeros in Excel CSV exports. Learn Power Query import steps and a Python BOM script, then verify field lengths with Python.

Double-clicking an exported CSV file in Microsoft Excel frequently triggers two separate defects. Non-ASCII characters display as corrupted mojibake, and postal codes such as 01001 or product SKU codes such as 0012 drop their leading zeros to become 1001 and 12.

Character corruption occurs because Excel assumes the system ANSI code page when opening a CSV without a UTF-8 Byte Order Mark (BOM). Leading zero loss occurs because Excel scans columns and forcibly coerces numeric-looking text into integers. Prepending a BOM fixes character encoding during double-click, but does not prevent Excel from stripping leading zeros. For related workflows on converting pasted tables into verified CSV structures, see Converting pasted tables to CSV and validating columns.

[1] Prepare a 10-row sample CSV representing order exports. Both the 5-digit ZIP codes and 4-digit product codes start with leading zeros.

orders_en.csv
OrderNumber,OrderDate,CustomerName,ZipCode,ProductCode,TotalAmountORD-20261014-001,2026-10-14 09:12:00,Oliver Smith,01001,0012,45.00ORD-20261014-002,2026-10-14 09:34:21,Emma Johnson,02138,0045,128.00ORD-20261014-003,2026-10-14 10:05:12,Liam Williams,08501,0089,32.00ORD-20261014-004,2026-10-14 10:22:45,Sophia Brown,01234,0105,78.00ORD-20261014-005,2026-10-14 11:15:30,Noah Jones,04520,0003,15.00… (10 rows total)

[2] Construct the prompt. Follow the Anthropic recommendation to place data context at the top, and apply the OpenAI guide principle of delimiting data blocks with XML tags.

text
<csv_data>{Exported CSV first 10 rows}</csv_data> The above <csv_data> is a UTF-8 encoded CSV file exported from an e-commerce management system.When double-clicking this CSV file to open it in Microsoft Excel, special characters can be garbled, and leading zeros in ZipCode (e.g., 01001) and ProductCode (e.g., 0012) are dropped as Excel automatically converts them to numeric values. Please provide a clear, practical guide with the following 4 sections:1. Root Cause Summary: Explain separately why characters garble (lack of UTF-8 BOM) and why leading zeros disappear (Excel automatic numeric type coercion) in 1-2 sentences each.2. Safe Import into Excel: Step-by-step instructions using Excel Power Query (Data > From Text/CSV) to set file origin to UTF-8 and enforce ZipCode and ProductCode columns as Text data type.3. Python Conversion Script: A concise Python one-liner (or short script) to prepend UTF-8 BOM to the CSV file.4. Caution: The irreversible data loss risk of opening and saving (Ctrl+S) the file in Excel, and how to recover if this happened.

[3] Execute the prompt under clean settings without external system instruction drift.

console
$ claude -p --model claude-sonnet-5-5 --max-turns 1 --tools "" --setting-sources "" --strict-mcp-config < run/csv-excel-en.prompt.txt > run/csv-excel-en.out.1.txt

Output from the run:

output
## 1. Root Cause Summary - **Garbled characters:** Excel opens a double-clicked CSV using the system ANSI code page (e.g. CP949 or CP1252) unless the file starts with a UTF-8 BOM (`EF BB BF`). Without the BOM, multi-byte UTF-8 sequences are misread as separate legacy characters.- **Dropped leading zeros:** On open, Excel infers each cell's type, and `01001` or `0012` looks like a number, so it is stored as the number `1001` or `12`. The zeros are discarded at that point and are not just hidden. A BOM fixes only the garbling. The leading zeros still need the Power Query import below. ## 2. Safe Import into Excel (Power Query) 1. Open a blank workbook (do not double-click the CSV).2. Go to **Data > From Text/CSV**.3. Select the CSV file and click **Import**.4. In the preview dialog:   - **File Origin:** `65001: Unicode (UTF-8)`   - **Delimiter:** Comma   - **Data Type Detection:** **Do not detect data types**5. Click **Transform Data** to open the Power Query Editor.6. If a **Changed Type** step exists under *Applied Steps*, delete it with the X. It would have already converted the columns to numbers.7. Ctrl+click the **ZipCode** and **ProductCode** headers, then choose **Transform > Data Type > Text**. If prompted, choose **Replace current**.8. Optionally set the other types: `OrderNumber` as Text, `OrderDate` as Date/Time, `TotalAmount` as Decimal Number.9. Click **Home > Close & Load**. Use **Data > Refresh All** to re-import an updated CSV with the same settings. Save the result as `.xlsx`, not `.csv`. ## 3. Python Conversion Script … The script works on raw bytes, so line endings and content are unchanged. Opening `orders_bom.csv` by double-click will show correct characters, but ZipCode and ProductCode will still lose their zeros, so use the Power Query import for those. ## 4. Caution: Do Not Save the CSV from Excel If you double-click the CSV, then press **Ctrl+S** and accept "Keep using that format", Excel overwrites the original file with what is in memory. This causes permanent loss: - `01001` becomes `1001` and `0012` becomes `12`.- `OrderDate` is rewritten in a locale format such as `10/14/2026 9:34`, and the seconds are dropped.- `45.00` becomes `45`.- Saved as plain "CSV (Comma delimited)", characters outside the ANSI code page become `?`. These cannot be recovered. **Recovery, in order of reliability:** 1. **Re-export** from the e-commerce system. This is the only complete fix.…

The script the model wrote for step 3 is a code block, so the block above cuts it with …. The file below, run/make_bom_en.py, was written for this article to do the same job, and it produced orders_en_bom.csv.

run/make_bom_en.py
from pathlib import Path here = Path(__file__).parentsrc = here / "orders_en.csv"dst = here / "orders_en_bom.csv" data = src.read_bytes()if not data.startswith(b"\xef\xbb\xbf"):    data = b"\xef\xbb\xbf" + datadst.write_bytes(data)print(f"Created {dst.name} with BOM, size={len(data)} bytes")
console
$ python run/make_bom_en.py

The second run (csv-excel-en.out.2.txt) gave the same root-cause summary but a different Power Query procedure. Both runs say Transform > Data Type > Text; run 1 adds "Replace current" and run 2 "Add new step". The Python in step 3 differs too: run 2 uses encoding="utf-8-sig" instead of raw bytes. For recovery, run 2 adds zfill(5) next to the Excel formulas. On saving, run 1 says to save the result as .xlsx; run 2 says to work in the loaded .xlsx and, if a CSV is needed, to save as CSV UTF-8.

[4] Build a verification script. It checks for the UTF-8 BOM bytes (EF BB BF), 5-digit ZIP codes, 4-digit product codes, duplicate order numbers, and amounts that are numbers. It does not look at the header names, date format or empty customer names, so errors there go unnoticed.

run/verify_en.py
import csv, math, sys raw = open(sys.argv[1], "rb").read()rows = list(csv.reader(raw.decode("utf-8-sig").splitlines()))[1:]errors, seen = [], set()if not raw.startswith(b"\xef\xbb\xbf"):    errors.append("no BOM")for n, (oid, _, _, zip_, code, amount) in enumerate(rows, start=1):    if oid in seen:        errors.append(f"row {n}: duplicate order number {oid}")    seen.add(oid)    if len(zip_) != 5 or not zip_.isdigit():        errors.append(f"row {n}: ZIP {zip_!r} is not 5 digits")    if len(code) != 4 or not code.isdigit():        errors.append(f"row {n}: product code {code!r} is not 4 digits")    try:        if not math.isfinite(float(amount.strip())):            raise ValueError    except ValueError:        errors.append(f"row {n}: amount {amount!r} is not a number")print(f"{sys.argv[1]}: {len(rows)} rows, {len(errors)} errors")for e in errors[:3]:    print("  *", e)sys.exit(1 if errors else 0)

[5] Run it against the BOM-prefixed export and two hand-made defect files. orders_en_bad_zeros.csv has the leading zeros stripped; orders_en_bad_dup.csv has a duplicated order number and a NaN amount. The output below is from the script, not from the model.

console
$ python run/verify_en.py run/orders_en_bom.csv$ python run/verify_en.py run/orders_en_bad_zeros.csv$ python run/verify_en.py run/orders_en_bad_dup.csv
output
run/orders_en_bom.csv: 10 rows, 0 errorsrun/orders_en_bad_zeros.csv: 10 rows, 21 errors  * no BOM  * row 1: ZIP '1001' is not 5 digits  * row 1: product code '12' is not 4 digitsrun/orders_en_bad_dup.csv: 10 rows, 3 errors  * no BOM  * row 2: duplicate order number ORD-20261014-001  * row 4: amount 'NaN' is not a number

The exit code was 0 for the BOM file and 1 for both defect files (the script does not print it). The defect files have no BOM either, so a no BOM error always comes first; the script prints only the first three errors. The amount check rejects NaN, inf, -inf, values that overflow to infinity such as 1e999, and values with surrounding spaces; four such rows in run/orders_bad_amount.csv were all caught (run/verify_amount.out.txt).

[6] Where it falls short. The model's Python script prepends EF BB BF, which fixes only the garbled characters. With Excel's default settings, double-clicking a file that has a BOM still turns 01001 into the number 1001 and drops the zero. Microsoft documents an "Automatic data conversion" setting under File > Options > Data (Excel for Microsoft 365, Excel 2024 and Excel 2021) whose leading-zero option can be switched off (Data import and analysis options in Excel). This run did not test an Excel with that option off, so for shared files and PCs where you cannot change the option, import through Power Query.

For a file that was double-clicked and overwritten with Ctrl+S, the model says characters outside the ANSI code page are saved as ? and cannot be recovered; that was not confirmed in this run. Fixed-width codes can be re-padded with =TEXT(), but a column with mixed lengths cannot be trusted that way, so re-export from the source system. This run did not open Excel itself; the description rests on the model's answer and Microsoft's documentation.

#csv#excel#encoding#data-cleaning#prompt