How to add CSV export — and why Excel shows gibberish

A "Download CSV" button is one of those things AI writes in ten seconds — and then you spend half a day working out why your accountant sent a screenshot full of hieroglyphs.
The file looks fine. Notepad opens it fine. But Excel shows Заказ instead of the customer's name. The culprit is one invisible character that isn't in your file.
Let's walk through it — traps included.
Step 1. Decide where the file gets built
Two options, and the choice is easy.
- On the client (in the browser). The data is already on the page; export just saves what you see. Nothing needed on the server, instant.
- On the server. Lots of rows (tens of thousands), or the export must include data that isn't on screen. Then the browser simply downloads an endpoint's response.
Start with the client. Under a couple of tens of thousands of rows, that's plenty.
Step 2. Build an array of arrays
No "join with commas in a loop". First get a flat structure: the first array is the headers, then one array per row. If your data arrives from the database as objects, convert them to arrays explicitly — that way you control column order instead of trusting key order.
const rows = [
["Date", "Customer", "Comment", "Total"],
["2026-08-12", "Anna", 'Said: "I\'ll take two"', 4990],
];
Look at that comment in row two. It contains quotes — exactly the kind of value that breaks a naive export.
Step 3. Escape values the CSV way
This is the crucial step. CSV has a standard (RFC 4180) with just three rules:
- if a value contains a comma, a quote or a line break, wrap the whole value in double quotes;
- a quote inside a value is doubled:
"becomes""; - rows are separated by
\r\n.
Six lines that do all of it:
function toCsv(rows) {
const esc = (v) => {
const s = v === null || v === undefined ? "" : String(v);
return /[",\r\n]/.test(s) ? `"${s.replaceAll('"', '""')}"` : s;
};
return rows.map((r) => r.map(esc).join(",")).join("\r\n");
}
Check this against your own app: if you have text fields that users write into, they will contain commas and line breaks. Without escaping, one review spreads across five columns and shifts the whole table.
Step 4. Add the BOM — that invisible character
Here's the gibberish answer. When you double-click a .csv, Excel doesn't ask about encoding — it guesses, and by default it guesses your system's single-byte codepage, not UTF-8. Non-Latin text turns to mush.
The fix is a \uFEFF character at the very start of the file — a byte order mark (BOM). It's invisible, a couple of bytes long, and it tells Excel immediately: this is UTF-8.
const csv = "\uFEFF" + toCsv(rows);
One line, and a problem that eats hours disappears.
Step 5. Hand the file over
On the client, via a Blob and an ordinary link:
const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = `orders-${new Date().toISOString().slice(0, 10)}.csv`;
a.click();
URL.revokeObjectURL(a.href);
The date in the filename is a small thing people thank you for: no folder full of export (3).csv.
On the server, send two headers and the browser does the rest:
Content-Type: text/csv; charset=utf-8
Content-Disposition: attachment; filename="orders-2026-08-12.csv"
Step 6. Test it in three places
CSV is a deceptive format: it "works" right up until someone opens it in something else. Check your export in Excel, in Google Sheets, and in Numbers if you have a Mac. Use real data, not test test — you specifically want the quotes, commas and long text.
What you get: the user clicks a button, gets a file, double-clicks it — and sees a normal table with readable text where no row has drifted sideways.
Two traps AI won't warn you about
Leading zeros and long numbers. Excel treats cell contents as numbers whenever it can. 007 becomes 7, a phone number like +79991234567 turns into scientific notation, and an SKU like 1-2 may become a date. If a field is conceptually text, you have to deal with it explicitly: either don't export such fields as bare numbers, or tell users to import the file rather than double-click it.
CSV injection. Much more serious. If a value starts with =, +, - or @, a spreadsheet may treat it as a formula — and evaluate it on the machine of whoever opens the file. Which means a user can type a formula into a "Name" field and have it run on someone else's computer. The fix is easy: prefix such values with an apostrophe before export, or force-quote them.
Both traps are a neat example of why AI-written code looks fine and still breaks: the model writes the happy path, and messy data isn't part of it.
How is CSV different from JSON?
CSV is a flat table for humans and Excel; JSON is a nested structure for programs. If your data has nesting, CSV forces you to flatten it, and some meaning is lost.
Why does Excel put my whole CSV in one column?
Most likely your locale expects a semicolon as the list separator instead of a comma. Either use ; as your separator, or import via "Data → From Text", where you pick encoding and separator by hand.
Do I need a library to export CSV?
To export, no — the function above is enough. To read someone else's CSV, do use a proper parser: that's where the whole zoo of encodings, separators and broken quotes lives.
The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.





