Convert CSV to Excel by API: declare the types your CSV lacks

A CSV has no types, so long IDs lose digits and day-first dates go wrong. A tested Python script declares each column and sends typed rows to the Excel API.

A CSV page with comma-separated text passes through a yellow box labelled types and becomes a spreadsheet grid whose columns are marked text, number and date

The JSON to Excel API takes JSON, not a CSV file. Read the CSV in your own code, declare a type for every column, and send typed rows. We tested the alternative: sent as plain text, a 20-digit ID lost its last digits and a day-first date stayed as text. With declared types, both came out right.

A CSV looks simple, but it carries no information about what each column means. Every value is text. The Excel writer has to decide whether 00123 is a number, whether 03/11/2026 is a date and which month it means. When it guesses, the guesses are conservative, and a few of them still cost you data. This guide shows what happens, the script that avoids it, and a check you can run on every file.

What the API does with an untyped value

When a column has no type, the service looks at each value and infers one. These are the current rules, and we checked each one on a real workbook:

  • A value that looks like a plain number, such as 42, -12.50 or 19.90, becomes a number. A leading zero keeps it as text, so 00123 stays text. A code such as 1E5 is read as scientific notation and becomes 100000.
  • An ISO date such as 2026-11-02 becomes a date.
  • A day-first date such as 03/11/2026 stays text. The service does not guess between day-first and month-first.
  • A number with a thousands separator, such as 1,234.50, stays text.
  • A string that starts with =, +, - or @ gets a leading apostrophe, so it cannot run as a formula. The apostrophe is stored in the cell text, so the cell shows it. The formula safety guide explains why.

The rules are sensible. They are also wrong for some CSV columns, as the next section shows.

The test: with and without declared types

We made a small CSV with two orders. It has a SKU with leading zeros, a 20-digit external ID, a price written as 5.00, a day-first ship date and a notes column with a line break and a value that starts with =. We turned it into a workbook two ways, with the generator package that powers the API, and read both workbooks back with openpyxl.

Column CSV value No declared types Declared types
sku 00123 text 00123 text 00123
big_id 12345678901234567890 number 12345678901234567000 text 12345678901234567890
price 5.00 number 5, shown as 5 number 5, shown as 5.00
ship_date 03/11/2026 text 03/11/2026 date 2026-11-03
notes =HYPERLINK("http://example.com") text with a leading apostrophe text with a leading apostrophe

Two rows matter most. The 20-digit ID became a number and lost its last digits. Microsoft lists the number precision of Excel as 15 digits, so a longer identifier cannot survive as a number. It has to be text. The day-first date stayed text, which loses nothing, but it cannot be sorted or filtered as a date.

The sku and notes rows are the same in both variants. The leading zeros and the formula protection are safe without any work from you.

Do not declare a day-first column as a date

The tempting fix for the date column is type: "date". We tried it on 03/04/2026. The service read it as 4 March 2026, the month-first reading. A Mexican or European file means 3 April. The cell holds a valid date and the wrong one, and nothing tells you. A value like 31/12/2026, which cannot be month-first, stayed as text.

So convert day-first dates in your own code, where you know the format of your file, and send ISO dates. The script below does it with one strptime call per value.

The script

It reads the CSV, checks every column against a schema, converts the values and sends one request. Install the one dependency with pip install requests.

import csv
import os
import uuid
from datetime import datetime

import requests

API = "https://api.justapi.tech"

# A CSV has no types, so you declare them, one entry per column.
# "parse" is read by this script only. It is not sent to the API.
SCHEMA = {
    "sku": {"type": "string"},        # identifier: keep the leading zeros
    "customer": {"type": "string"},
    "big_id": {"type": "string"},     # 20 digits: Excel keeps only 15 in a number
    "qty": {"type": "number"},
    "price": {"type": "number", "format": "0.00"},
    "ordered": {"type": "date"},      # already ISO, yyyy-mm-dd
    "ship_date": {"type": "date", "parse": "%d/%m/%Y"},  # day first: convert here
    "notes": {"type": "string"},
}


def convert(value, spec):
    if value == "":
        return None
    if spec["type"] == "number":
        return float(value) if "." in value else int(value)  # "1,234.50" raises: clean it first
    if spec["type"] == "date" and "parse" in spec:
        return datetime.strptime(value, spec["parse"]).date().isoformat()
    return value


def payload_from_csv(path, sheet_name="Orders"):
    # newline="" lets the csv module keep line breaks inside quoted cells.
    # utf-8-sig drops the byte order mark that Excel adds to a CSV.
    with open(path, newline="", encoding="utf-8-sig") as fh:
        reader = csv.DictReader(fh)
        unknown = [name for name in reader.fieldnames if name not in SCHEMA]
        if unknown:
            raise ValueError(f"columns without a declared type: {unknown}")
        rows = [{k: convert(v, SCHEMA[k]) for k, v in row.items()} for row in reader]
        columns = [
            {"header": name, "key": name, **{k: v for k, v in SCHEMA[name].items() if k != "parse"}}
            for name in reader.fieldnames
        ]
    return {"sheets": [{"name": sheet_name, "columns": columns, "rows": rows}]}


def csv_to_xlsx(path, out_path):
    payload = payload_from_csv(path)
    expected = len(payload["sheets"][0]["rows"])
    res = requests.post(
        f"{API}/v1/xlsx/generate",
        headers={
            "Authorization": f"Bearer {os.environ['JUSTAPI_KEY']}",
            "Idempotency-Key": str(uuid.uuid4()),
        },
        json=payload,
        timeout=120,
    )
    res.raise_for_status()
    body = res.json()
    if body["stats"]["rows"] != expected:
        raise RuntimeError(f"sent {expected} rows, the workbook has {body['stats']['rows']}")
    file = requests.get(body["result"]["url"], timeout=60)  # signed link, no key needed
    file.raise_for_status()
    with open(out_path, "wb") as fh:
        fh.write(file.content)
    return body["result"]

Four choices in it are worth a line each:

  • The schema is required. A column that is not in SCHEMA stops the run. A new column in next month's export is then a decision, not a surprise.
  • newline="" and utf-8-sig. The first keeps line breaks that sit inside quoted cells. The second removes the byte order mark that Excel writes at the start of a CSV, which would otherwise end up in the first header.
  • Empty cells become null. An empty value must not reach float("") in a number column. A null leaves the cell empty in the workbook.
  • Thousands separators fail loudly. float("1,234.50") raises an error. You clean the column on purpose, because 1,234 is one thousand two hundred and thirty-four in one country and one point two three four in another.

The response has a stats.rows field. The script compares it with the number of rows it sent, and stops when they differ. The count is data rows only, the header is not included.

What we ran

We ran the script's conversion on the sample CSV, which has a byte order mark and Windows line endings. We turned the result into a workbook with the generator package and read it with openpyxl. We ran the request and download code against a local stub that answers like the API. The stub confirmed that the key and the idempotency header are sent and that the parse hint is not. The row check raised an error when the stub reported one row too few. The schema check raised on an unknown column, and the conversion raised on 1,234.50.

We did not call the live service for this article. Run the script once on a small file with your own key and open the result in Excel before you trust it with a real export.

Things the output does not do for you

  • The line break is stored, not shown. The cell keeps the line break from the CSV. It is not set to wrap, so Excel shows the break only after a user turns on Wrap Text.
  • Retries make a new job. The script makes a new idempotency key on each run. If you retry on a timeout, derive the key from the file, for example its hash, so the same file is the same job. The idempotency guide shows how.
  • The row limit still applies. The API accepts up to 200,000 data rows per workbook. For a bigger CSV, split it. The Node.js and Python guide covers the limits and the cost.

Before you ship

  1. Write the schema from the meaning of each column, not from the first ten rows.
  2. Keep identifiers longer than 15 digits as text.
  3. Convert every non-ISO date in your code, and never rely on the API to pick between day-first and month-first.
  4. Compare stats.rows with the row count of the CSV.
  5. Open one generated file and look at it.

For styles such as a bold header, a frozen header row and column widths, read the styles guide. To try the API, start free. New accounts get 1 USD of credit with no card.