skip to content

In pandas, how do you read every sheet of an Excel workbook, what does read_excel return, and how do you write several sheets back?

level: middleimportance: should knowfreq 50%

answer

  1. the default reads one sheet
  2. None changes the return type
  3. one file, one writer
  4. context manager saves the workbook

basics

~10 s

pd.read_excel(path, sheet_name=None) returns a dict of DataFrames keyed by sheet name; the default sheet_name=0 reads only the first sheet. To write several sheets, open one pd.ExcelWriter and call to_excel(writer, sheet_name=...) per frame.

solid answer

~30 s

`read_excel` defaults to `sheet_name=0`, the first sheet as a DataFrame. `sheet_name=None` reads every sheet and returns a dict mapping sheet name to DataFrame; a list returns a dict too, keyed by what you passed. Writing is the mirror trap: `df.to_excel(path, sheet_name=...)` creates a fresh workbook each time, so two calls leave only the second sheet. For a multi-sheet report I open `with pd.ExcelWriter(path) as writer:` and call `to_excel(writer, sheet_name='Summary', index=False)` for each frame; the file is saved when the writer closes. To add a sheet to an existing workbook I use `mode='a'` with `engine='openpyxl'` and an `if_sheet_exists` policy.

code

python · 19 lines
python
import os
import tempfile

import pandas as pd

summary = pd.DataFrame({"region": ["North", "South"], "revenue": [1200.0, 950.0]})
detail = pd.DataFrame({"invoice": ["A-1", "A-2", "B-7"], "amount": [400.0, 800.0, 950.0]})

with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "q3_report.xlsx")
    with pd.ExcelWriter(path) as writer:
        summary.to_excel(writer, sheet_name="Summary", index=False)
        detail.to_excel(writer, sheet_name="Detail", index=False)

    first = pd.read_excel(path)  # sheet_name=0: a DataFrame
    sheets = pd.read_excel(path, sheet_name=None)  # every sheet: a dict
    print(type(first).__name__, first.shape)  # DataFrame (2, 2)
    print(type(sheets).__name__, list(sheets))  # dict ['Summary', 'Detail']
    print(sheets["Detail"].shape)  # (3, 2)

go deeper

for a junior

Recall that read_excel reads the first sheet by default and that sheet_name picks another one by name or position.

for a middle

Explain that sheet_name=None or a list returns a dict, and that several sheets are written through one ExcelWriter used as a context manager.

for a senior

Show the production habits: append mode with openpyxl, an explicit if_sheet_exists policy, index=False, and pinning dtypes on human-edited sheets.

for a principal

Keep Excel at the edge of a pipeline, for people, and decide which validated format the data travels in between jobs.

## Reading a workbook: `sheet_name` `pd.read_excel(io, sheet_name=0, *, header=0, index_col=None, usecols=None, dtype=None, engine=None, skiprows=None, nrows=None, ...)` reads Excel (`xls`, `xlsx`, `xlsm`, `xlsb`) and OpenDocument files. The **shape of the result depends on `sheet_name`**: | `sheet_name` | returns | |---|---| | `0` (default) | the **first** sheet as a DataFrame | | `1` | the second sheet as a DataFrame (positions are zero-based; chart sheets do not count) | | `"Summary"` | that named sheet as a DataFrame | | `[0, 1, "Q3"]` | a **dict** of DataFrames, keyed by the items you passed | | `None` | a **dict** of DataFrames for **every** sheet, keyed by sheet name | So a finance team's workbook with a Summary sheet and twelve monthly sheets is read in one call with `sheet_name=None`, and the code then works on a dict, not a DataFrame. Calling `.head()` on that result is the classic `AttributeError`. To stack the monthly sheets, pass the dict to `pd.concat`, whose `keys` come from the dict keys. Other arguments that matter for human-made sheets: - **`header`** and **`skiprows`** step over title rows above the real header. - **`usecols`** accepts Excel letters and ranges such as `"A:E"` or `"A,C,E:F"`, as well as names, positions or a callable. - **`dtype`** pins types; `dtype=object` keeps cells exactly as stored. - **`engine`** defaults by file type: `odf` for OpenDocument, `xlrd` for old `.xls`, `pyxlsb` for `.xlsb`, otherwise `openpyxl`; `calamine` reads `.xls`, `.xlsx`, `.xlsm`, `.xlsb` and `.ods`. - `pd.ExcelFile(path)` opens the workbook once and exposes `sheet_names`, which helps when you only need some sheets of a large file. ## Writing several sheets: `ExcelWriter` `DataFrame.to_excel(excel_writer, *, sheet_name='Sheet1', index=True, ...)` given a **path** creates a new workbook containing one sheet. Two consecutive calls with the same path do not add a second sheet: the second call writes a new file over the first. The docstring is explicit that writing to multiple sheets needs an **`ExcelWriter`**: ```python with pd.ExcelWriter("q3_report.xlsx") as writer: summary.to_excel(writer, sheet_name="Summary", index=False) detail.to_excel(writer, sheet_name="Detail", index=False) ``` Points to remember: - Use `ExcelWriter` as a **context manager**, or call `close()`; the file is saved when the writer closes. - Creating an `ExcelWriter` on an existing file name **overwrites** that file, because the default `mode` is `'w'`. - `index=True` is the default in `to_excel` as well, so pass `index=False` unless the row labels belong in the report. - The default engine for `.xlsx` is `xlsxwriter` if installed, otherwise `openpyxl`. ## Adding to an existing workbook `pd.ExcelWriter(path, mode='a', engine='openpyxl', if_sheet_exists=...)` opens a workbook to add or change sheets. `mode='a'` is not supported by the `xlsxwriter` or `odf` writers, so name `openpyxl`. `if_sheet_exists` applies only in append mode: 1. `'error'` (default) raises `ValueError` when the sheet exists. 2. `'new'` creates a new sheet with a name chosen by the engine. 3. `'replace'` deletes the sheet's contents before writing. 4. `'overlay'` writes over the existing cells without clearing them first, so old values outside the new frame's area remain. The docstring also notes that once a workbook has been saved, further data cannot be written without rewriting the whole workbook; append mode reads it in and writes it back. ## Headers, merged cells and types on human-made sheets Finance workbooks are built for reading, not parsing, and `read_excel` has arguments for the usual decorations: - A title block above the table: `skiprows=3` or `header=3`, and `nrows=` to stop before a totals row; `skipfooter=` drops trailing rows. - Merged row labels: with `index_col=`, `read_excel` forward-fills the missing values so merged cells round-trip with `to_excel(merge_cells=True)`; to avoid that fill, read without `index_col` and call `set_index` afterwards. - Codes that look numeric (cost centres, account numbers): `dtype={"cost_centre": "str"}`, or `converters=` for a per-cell function, which is applied instead of `dtype`. - Placeholder text such as `"n/a"` or `"-"`: `na_values=`, with `keep_default_na` deciding whether the built-in markers still count. Each sheet of a `sheet_name=None` read gets the same arguments, so a workbook whose sheets have different layouts is read sheet by sheet instead. ## Common mistakes - Treating the dict from `sheet_name=None` as a DataFrame. - Calling `to_excel(path)` once per sheet and shipping a one-sheet file. - Using `mode='a'` with the default `xlsxwriter` engine and getting a `ValueError`. - Using `'overlay'` to refresh a sheet whose new data is shorter than the old, leaving stale rows underneath.

  • How do you combine the twelve monthly sheets into one DataFrame with a month column?
    Read them with `sheet_name=None` (or a list of the month sheet names), drop the Summary key from the dict, and pass the dict to `pd.concat`; the dict keys become the outer index level, which `reset_index` turns into a column you can rename to `month`.
  • The report needs a new sheet added to last quarter's workbook. What changes?
    Open `pd.ExcelWriter(path, mode='a', engine='openpyxl', if_sheet_exists='replace')`. Append mode is not supported by the xlsxwriter or odf writers, and `if_sheet_exists` only applies in append mode; 'replace' clears an existing sheet of that name before writing.

to_excel with a path is printing a brand-new binder for every call, so the second print replaces the first; ExcelWriter keeps one binder open while you slide in each tab, and closing it is what puts the binder on the shelf.

  • Believes read_excel reads every sheet unless told otherwise
  • Calls to_excel(path) once per sheet and expects one workbook with all of them
  • Treats the result of sheet_name=None as a single DataFrame
  • Uses mode='a' with the default xlsxwriter engine
  • Thinks if_sheet_exists='overlay' clears the old sheet first