DEV Community

Kayabyte
Kayabyte

Posted on

Why CSV files open wrong in Excel for Mac, and how to write ones that don't

You export a perfectly good CSV, someone double-clicks it in Excel, and they tell you it is broken. Names have strange characters, ZIP codes lost their first digit, a date moved from April to March, and a product code turned into a date. The file is fine. Excel is guessing, and the guesses are predictable once you know them.

I tested the cases below with Microsoft Excel 16.93 for Mac on macOS 27.2, opening a small CSV through Excel's own open command. The writer snippets in Python and Swift were run and their output bytes checked.

The test file

name,zip,ordered,code,card
Bjørn Ødegård,01234,03/04/2026,1-2,4111111111111111
Enter fullscreen mode Exit fullscreen mode

Here is what Excel made of row 2:

Column In the file In Excel
zip 01234 1234 (a number)
ordered 03/04/2026 (meant as 3 April) 4 March 2026, format m/d/yy
code 1-2 2 January 2026, format d-mmm
card 4111111111111111 a number in scientific notation (E+15)

Every one of these is a type guess. Let's go through them, then look at how to write files that avoid them.

1. Encoding and the UTF-8 BOM

A CSV has no header that says which text encoding it uses. Excel looks for a byte order mark: the three bytes EF BB BF at the very start of the file. With them, it knows the file is UTF-8. Without them, it may fall back to a legacy encoding, and ø comes out as two odd characters.

Excel's own "CSV UTF-8" save format writes the BOM, which is a good hint about what Excel expects to read. In Python, the utf-8-sig codec adds it for you:

with open("out.csv", "w", encoding="utf-8-sig", newline="") as f:
    ...
Enter fullscreen mode Exit fullscreen mode
$ xxd out.csv | head -1
00000000: efbb bf6e 616d 652c 7a69 702c 6e6f 7465  ...name,zip,note
Enter fullscreen mode Exit fullscreen mode

The catch: some non-Excel tools treat the BOM as part of the first header, so the first column becomes name. If your CSV is for a program rather than a person, ask what it wants. For files people open in Excel, I always add the BOM.

2. The delimiter depends on where you are

"Comma-separated" is a suggestion. In much of Europe the comma is the decimal mark, so spreadsheet apps there use a semicolon between fields. Excel for Windows takes the separator from the Windows regional "list separator" setting, which is why a comma CSV opens as one wide column for many European users, and a semicolon CSV opens as one column for Americans.

On my Mac, with Norwegian region settings and a decimal comma, Excel 16.93 still split a comma file into columns correctly. So the Mac seems more forgiving here than Windows. But you rarely control who opens your file, so choose the delimiter for the reader:

  • For a known European audience on Windows, write semicolons and decimal commas (1499,50).
  • For everyone else, write commas and decimal points, and quote any field that contains the delimiter, a quote or a line break.

There is also a convention of putting sep=; on the first line, which Excel for Windows reads as the delimiter. I have not confirmed it on the Mac, and every other CSV reader sees it as a data row, so I don't use it in files for mixed audiences.

3. Leading zeros and long numbers

ZIP codes, phone numbers, employee IDs, bank account numbers and barcodes look like numbers, so Excel makes them numbers. 01234 becomes 1234. Anything over 15 significant digits is worse: Excel stores numbers with 15 digits of precision, so a 16-digit card or account number does not just display in scientific notation, its last digit is lost and becomes 0. You cannot get it back by changing the cell format afterwards.

There is no reliable fix inside a plain CSV. The common trick is writing the value as ="01234", which Excel shows as text, but every other tool sees a formula string. The honest options are:

  • Tell the reader to import rather than open: Excel's text import on the Data tab lets you set those columns to Text before the data lands.
  • Or don't send a CSV. Send an XLSX where those cells are stored as text (more on that below).

4. Dates flip, and things that aren't dates become dates

03/04/2026 is 3 April in Norway and 4 March in the US. Excel picks one based on its settings, without telling you, and you now have a real date that is wrong by a month. In my test it read the US way, even with a Norwegian region on the Mac.

Then there are values that are not dates at all. 1-2, 3/4, MAR1, SEPT2 and similar codes get converted. Genetics researchers famously renamed some human genes because Excel kept turning them into dates.

What works:

  • Write dates as ISO 8601: 2026-04-03. There is no day/month ambiguity for a human reading it, and spreadsheet apps generally recognise it as a date.
  • For codes that look like dates, you are back to XLSX with text cells, or the import route.

5. A small one: a file that starts with "ID"

If the first two characters of a CSV are a capital ID, Excel can decide it is a SYLK file and complain that the format is not valid. Microsoft has a support article on this. Rename the header to Id or id, or put another column first.

6. Formulas inside your data

Not a display problem, a safety one. A cell that starts with =, +, - or @ can be run as a formula when the file is opened. If your CSV contains text that users typed (names, comments, addresses), someone can put a formula there. The usual defence, also recommended by OWASP, is to prefix such cells with a single quote. It changes the data slightly, so apply it to free-text columns, not to columns where a minus sign means a negative number.

A CSV writer that gets most of this right

Python, standard library only:

import csv

def safe(value):
    s = "" if value is None else str(value)
    # Cells starting with these can be read as formulas by spreadsheet apps.
    if s[:1] in ("=", "+", "-", "@", "\t", "\r"):
        return "'" + s
    return s

rows = [["name", "zip", "note"],
        ["Bjørn Ødegård", "01234", '=HYPERLINK("http://example.com")'],
        ["Ann", "05000", "line one\nline two, with a comma"]]

with open("out.csv", "w", encoding="utf-8-sig", newline="") as f:
    w = csv.writer(f, delimiter=",", quoting=csv.QUOTE_MINIMAL, lineterminator="\r\n")
    for r in rows:
        w.writerow([safe(v) for v in r])
Enter fullscreen mode Exit fullscreen mode

The output starts with the BOM, uses CRLF line endings (what Excel writes itself), quotes the field with the embedded comma and newline, doubles the inner quotes, and turns the formula into '=HYPERLINK(...).

The same in Swift. Note that I check Unicode scalars, not Characters: in Swift, "\r\n" is a single Character, so contains("\n") on a String can miss it.

import Foundation

func csvField(_ s: String, delimiter: Unicode.Scalar = ",") -> String {
    var v = s
    if let first = v.unicodeScalars.first, "=+-@\t\r".unicodeScalars.contains(first) { v = "'" + v }
    let needsQuotes = v.unicodeScalars.contains { $0 == delimiter || $0 == "\"" || $0 == "\n" || $0 == "\r" }
    if needsQuotes { v = "\"" + v.replacingOccurrences(of: "\"", with: "\"\"") + "\"" }
    return v
}

func writeCSV(_ rows: [[String]], to url: URL, delimiter: Unicode.Scalar = ",") throws {
    let sep = String(Character(delimiter))
    var text = ""
    for row in rows {
        text += row.map { csvField($0, delimiter: delimiter) }.joined(separator: sep) + "\r\n"
    }
    var data = Data([0xEF, 0xBB, 0xBF])   // UTF-8 byte order mark
    data.append(Data(text.utf8))
    try data.write(to: url, options: .atomic)
}
Enter fullscreen mode Exit fullscreen mode

This still cannot protect leading zeros or date-like codes. For that you need a format with types.

Writing XLSX instead

An XLSX file stores each cell's type, so you decide what is text, what is a number and what is a date, and Excel does not guess. With openpyxl (pip install openpyxl):

from datetime import date
from openpyxl import Workbook

wb = Workbook()
ws = wb.active
ws.title = "Orders"
ws.append(["name", "zip", "ordered", "code", "card", "amount"])
ws.append(["Bjørn Ødegård", "01234", date(2026, 4, 3), "1-2", "4111111111111111", 1499.5])

for row in ws.iter_rows(min_row=2):
    row[1].number_format = "@"           # zip stays text
    row[2].number_format = "yyyy-mm-dd"  # a real date, shown without ambiguity
    row[3].number_format = "@"
    row[4].number_format = "@"
    row[5].number_format = "#,##0.00"

ws.freeze_panes = "A2"
wb.save("orders.xlsx")
Enter fullscreen mode Exit fullscreen mode

Reading it back with openpyxl confirms the types: '01234' is a string, the date is a date, '4111111111111111' is a string with all 16 digits, and the amount is a number. Passing Python strings is what keeps them as text; the @ format additionally keeps them as text if someone edits the cell later.

Summary

  • Add a UTF-8 BOM for files people open in Excel.
  • Pick the delimiter for your reader; quote properly; use CRLF.
  • Write dates as yyyy-mm-dd.
  • Guard free-text cells against formulas.
  • Anything with leading zeros, more than 15 digits, or date-like codes: send XLSX with text cells, not CSV.

Disclosure: I make Gridhand, a Mac app for batch Excel and CSV jobs. Its Convert tool turns many CSV files into XLSX with encoding and delimiter detection and leading-zero IDs kept as text, and writes CSV with a BOM and formula protection. It has unlimited previews and two free runs, on the Mac App Store or direct.

Written with help from an AI assistant; code and commands were tested on macOS.

Top comments (0)