Write and download

to_csv, to_json, to_excel, and the workbench download chip.

Writes go to /uploads. After Run, click on the file chip. The workbench may also start a download. Nothing leaves this browser unless you save the file yourself.

Goal

Export CSV, JSON, and (when openpyxl is ready) Excel, with clean headings and no leftover index column unless you want it.

CSV

import os

df = pd.DataFrame(
    {
        "city": ["Nairobi", "Mombasa", "Kisumu"],
        "revenue": [280.0, 136.5, 273.5],
    }
)
df.to_csv("city_revenue.csv", index=False)
print("wrote city_revenue.csv")
print(os.listdir("/uploads"))
print(pd.read_csv("city_revenue.csv"))

index=False drops the 0,1,2 column. Keep the index only when it is a meaningful key (to_csv("out.csv") default index=True).

JSON

df = pd.DataFrame(
    {
        "city": ["Nairobi", "Mombasa", "Kisumu"],
        "revenue": [280.0, 136.5, 273.5],
    }
)
df.to_json("city_revenue.json", orient="records")
print(pd.read_json("city_revenue.json"))

orient="records" is a list of objects. orient="table" is heavier but preserves dtypes.

Excel

df = pd.DataFrame(
    {
        "city": ["Nairobi", "Mombasa", "Kisumu"],
        "revenue": [280.0, 136.5, 273.5],
    }
)
df.to_excel("city_revenue.xlsx", index=False)
print("wrote city_revenue.xlsx")

Needs openpyxl. If this errors, wait until the workbench status says Excel support is ready and run again.

Several sheets

by_city = pd.DataFrame({"city": ["Nairobi", "Mombasa"], "revenue": [280.0, 136.5]})
by_product = pd.DataFrame({"product": ["A", "B"], "revenue": [400.0, 290.0]})
with pd.ExcelWriter("report.xlsx") as writer:
    by_city.to_excel(writer, sheet_name="by_city", index=False)
    by_product.to_excel(writer, sheet_name="by_product", index=False)
print("wrote report.xlsx")

Formatting choices

df = pd.DataFrame(
    {
        "city": ["Nairobi", "Mombasa"],
        "revenue": [280.125, 136.5],
    }
)
df.to_csv("city_revenue.csv", index=False, float_format="%.2f")
print(open("/uploads/city_revenue.csv").read())
Tip

If the chip does not appear, print(os.listdir("/uploads")) and confirm the filename you wrote. Then click the chip’s download arrow.