Writing CSV Export Code With LLMs in November 2026: Let a Real CSV Library Quote, Block Formula Injection, and Stream Large Exports

"Add a button that downloads this table as CSV" sounds like the easiest ticket in the backlog, and a coding assistant will happily write it in seconds. Very often the result joins values with commas, adds a newline, and calls it done. It works on the demo data. Then a customer named "Smith, Jr." breaks the columns, a product note with a line break splits one row into two, and someone discovers that a cell starting with = runs as a formula when a colleague opens the file in a spreadsheet app.

CSV looks trivial because it is plain text. The hard parts are quoting, encoding, the spreadsheet apps that will open the file, and the size of real exports. This guide shows how to get an LLM to write CSV export code that survives real data, and how to test it before your users find the gaps.

A wooden library card catalog cabinet with many small drawers

Every record in its own drawer and every field in its own slot. A CSV library keeps your columns just as tidy. Image: Wooden Card Catalog Furniture by MarkBuckawicki, CC0, via Wikimedia Commons.

Why LLM-written CSV export code breaks

Models have seen a huge amount of quick-and-dirty CSV code, so that is what they reach for unless you ask for something better. The usual problems are:

  • Hand-rolled joining. Code like ",".join(values) or a template string with commas between fields. Any comma, double quote, or newline inside a value corrupts the row.
  • No defense against formula injection. Values that start with =, +, -, or @ can be treated as formulas by spreadsheet software. If those values come from users, that is a security problem, not a formatting quirk.
  • Encoding left to chance. Names with accents or non-Latin scripts come out garbled when the file is opened in a spreadsheet app that guesses the wrong encoding.
  • Everything built in memory. The code loads every row, builds one giant string, and returns it. Fine for 200 rows, painful for 2 million.
  • No permission check on what gets exported. The export endpoint returns every row in the table instead of the rows this user is allowed to see.

None of these are exotic. They are what you get by default, so your prompt and your tests need to push against each one.

Step 1: Tell the model to use a real CSV library

The single most useful instruction is: do not build CSV lines by hand; use the language's CSV library. Almost every ecosystem has one that handles quoting correctly: Python's built-in csv module, Go's encoding/csv, Ruby's CSV, and well-maintained packages for Node.js, Java, and .NET.

The common convention, described in RFC 4180, is simple to state and easy to get wrong by hand:

  • A field that contains a comma, a double quote, or a line break must be wrapped in double quotes.
  • A double quote inside a quoted field is written as two double quotes.
  • Records are separated by line breaks (the RFC uses CRLF).

A library does all of this for you. Here is a minimal Python example that gets the quoting right:

import csv

def write_rows(file_obj, rows):
    writer = csv.writer(file_obj)  # default quoting handles commas, quotes, newlines
    writer.writerow(["id", "name", "note"])
    for row in rows:
        writer.writerow([row.id, row.name, row.note])

# When writing to a file, open it with newline="" so the csv module
# controls line endings itself:
with open("export.csv", "w", newline="", encoding="utf-8") as f:
    write_rows(f, rows)

That newline="" detail is documented in Python's csv docs and is exactly the kind of thing a model forgets. If you see it missing, ask for it. On Windows, leaving it out can produce blank lines between rows.

A good prompt for this step looks like:

Write a CSV export for the orders table in Python 3.12 using the
standard csv module. Do not join strings by hand. Columns: id,
customer_name, total, created_at. Values may contain commas, double
quotes, and newlines. Show the code and explain how quoting is handled.

Step 2: Block formula injection on purpose

CSV injection (also called formula injection) happens when a value that a user controls, such as a name, a comment, or a product title, starts with a character that a spreadsheet app treats as the start of a formula. When someone opens the export, the cell may be evaluated instead of shown as text. OWASP documents this risk and lists the characters to watch: =, +, -, @, tab, and carriage return.

Quoting does not fix this. A properly quoted field that starts with = is still a formula to the spreadsheet. The usual mitigation is to prefix risky values with a single quote so the app treats them as text, and to apply it to every user-controlled string column:

RISKY_PREFIXES = ("=", "+", "-", "@", "\t", "\r")

def safe_cell(value):
    if isinstance(value, str) and value.startswith(RISKY_PREFIXES):
        return "'" + value
    return value

writer.writerow([safe_cell(v) for v in (row.id, row.name, row.note)])

Be deliberate about where this applies. If a numeric column is exported as a real number, such as -42.50, prefixing it would turn a refund into text and break someone's totals. Apply the guard to string columns that come from users, and keep numeric columns as numbers. Tell the model which columns are which, because it cannot guess.

Also be honest about the trade-off: the prefix shows up in the data if someone imports the file into another system. That is usually acceptable for exports meant for humans in a spreadsheet. If the export feeds another program, agree on a format with that program's owner instead of silently changing values.

Step 3: Decide the encoding and the format details up front

Many CSV bugs are really undocumented decisions. Make them explicit in your prompt and in a comment at the top of the export code:

  • Encoding. Use UTF-8. If your users mostly open files in Microsoft Excel, consider writing a UTF-8 byte order mark (BOM) at the start of the file, because Excel may otherwise misread non-ASCII characters. In Python, the utf-8-sig encoding writes the BOM for you. If the file feeds scripts, a BOM can get in the way, so choose based on who opens it.
  • Delimiter. Commas are the default, but some regional spreadsheet settings expect semicolons. Pick one and document it rather than letting it vary.
  • Dates and times. Export ISO 8601 strings like 2026-11-16T08:00:00Z and say which time zone they are in. Never export whatever format the server locale happens to produce.
  • Numbers. Use a plain dot as the decimal separator, with no thousands separators and no currency symbols inside the number. Put the currency in its own column if it varies.
  • Leading zeros. ZIP codes, phone numbers, and account IDs like 00742 can lose their leading zeros when a spreadsheet app guesses they are numbers. If that matters to your users, say so in the export docs or offer a format that preserves types, such as XLSX.
  • Empty values. Decide whether missing values are an empty field or a literal like NULL, and keep it consistent.

Step 4: Stream large exports instead of building them in memory

An export that builds the whole file as one string has to hold every row in memory at once and makes the user wait until the last row is ready before the download even starts. For large tables, ask the model for a streaming version: read rows in batches from the database and write each batch out as it is produced.

In Python, a common pattern is a generator that yields CSV text one row at a time, which most web frameworks can send as a streaming response:

import csv, io

def csv_stream(rows):
    buf = io.StringIO()
    writer = csv.writer(buf)
    writer.writerow(["id", "name", "note"])
    yield buf.getvalue()
    buf.seek(0); buf.truncate(0)
    for row in rows:  # rows should be a server-side cursor or batched query
        writer.writerow([row.id, safe_cell(row.name), safe_cell(row.note)])
        yield buf.getvalue()
        buf.seek(0); buf.truncate(0)

Two things to check in whatever the model writes:

  1. The query really streams. A generator does not help if the line above it called .all() and loaded every row. Ask the model to use your database driver's server-side cursor or batched fetching, and name your ORM so it uses the right API.
  2. Very large exports go to a background job. If an export can take minutes, a long-running HTTP request is fragile. Generate the file in a background job, store it, and send the user a link when it is ready. Ask the model for that design if your largest export is big enough to need it.
Output card stackers on an IBM 1402 card reader-punch at the Computer History Museum

Punched-card machines produced output one card at a time. Large exports should stream row by row the same way. Image: IBM 1402 output stackers CHM by ArnoldReinhold, CC BY 4.0, via Wikimedia Commons.

Step 5: Export only what this user may see

Exports are a classic place for data leaks because they are "just a download." The export endpoint should apply the same filters and permission checks as the screen it came from. If the page shows one customer's orders, the CSV should contain one customer's orders, not the whole table.

When you prompt, include the existing query or view the page uses and ask the model to reuse it. Then read the generated query yourself and confirm it filters by the current user or account. Also decide which columns belong in the export: internal IDs, email addresses, and notes fields may be fine on screen for staff but not in a file that gets forwarded around.

Step 6: Test with nasty data, then open the file

The fastest way to find CSV bugs is a small fixture of deliberately awkward rows. Ask the model to generate tests around a list like this, and add your own from real support tickets:

  • A name with a comma: Smith, Jr.
  • A value with double quotes: The "best" plan
  • A note with an embedded line break
  • Non-ASCII text: José, Zürich, 東京
  • Values starting with =, +, -, and @
  • A negative number in a numeric column, which must stay a number
  • An ID with leading zeros
  • An empty value and a missing value

Then write a round-trip test: export the fixture, parse the output back with the same CSV library, and assert that every field matches what you put in (apart from the deliberate formula-guard prefix). A round trip catches broken quoting immediately.

def test_round_trip(tmp_path):
    path = tmp_path / "out.csv"
    with open(path, "w", newline="", encoding="utf-8") as f:
        write_rows(f, FIXTURE_ROWS)
    with open(path, newline="", encoding="utf-8") as f:
        parsed = list(csv.reader(f))
    assert parsed[0] == ["id", "name", "note"]
    assert len(parsed) == len(FIXTURE_ROWS) + 1  # no rows split by newlines
    assert parsed[1][1] == "Smith, Jr."

Finally, do the test that no unit test replaces: open the file in the spreadsheet apps your users actually use. Check that the accented names look right, the formula-looking values show as text, the row count matches, and the dates are readable. It takes two minutes and catches encoding problems that pass every automated check.

A reusable prompt for CSV export code

Write a CSV export for [table/view] in [language + version, framework,
ORM]. Requirements:
- Use the standard CSV library; never join strings by hand.
- Columns: [list], with types. Numeric columns stay numeric.
- Prefix user-controlled string values that start with =, +, -, @,
  tab, or carriage return with a single quote.
- UTF-8 [with/without BOM]; comma delimiter; ISO 8601 UTC timestamps.
- Stream rows in batches using a server-side cursor; do not load all
  rows into memory.
- Reuse this query so the export only includes rows the current user
  may see: [paste query].
- Include tests: a round-trip test with commas, quotes, newlines,
  non-ASCII text, formula-like values, negative numbers, and leading zeros.

The short version

CSV export is easy to write and easy to get subtly wrong. Get an LLM to use a real CSV library instead of joining strings, guard user-controlled values against formula injection, decide encoding and formats explicitly, stream large exports, and apply the same permissions as the page the data came from. Then prove it with a round-trip test over nasty data and a quick look in a real spreadsheet app. That turns a "five-minute ticket" into an export your users can trust.

Comments

Popular posts from this blog

Grok Bot - a step closer to AGI

Tencent Hy4 Preview: Open 770B MoE Built for Real Work

Structured Outputs and Constrained Decoding for Reliable LLM APIs in Production (September 2026)