← Back to Pandas Course | Chapter 11: File I/O | Lesson 2 of 7

read_excel/to_excel

read_excel loads a worksheet from an Excel file and to_excel saves a DataFrame to one.

In this page:

  1. read_excel/to_excel
Syntax
python
df = pd.read_excel("file.xlsx", sheet_name="Sheet1")
df.to_excel("out.xlsx", index=False)

read_excel/to_excel

Reading and writing .xlsx files needs the openpyxl engine installed. read_excel accepts sheet_name, header and usecols. to_excel can write several sheets through an ExcelWriter. In this example an in-memory buffer stands in for a file.

Note: sheet_name=None reads every sheet into a dictionary.

Example: read_excel/to_excel

python
import io
import openpyxl
import pandas as pd

df = pd.DataFrame({"item": ["pen", "ink"], "qty": [10, 3]})
buf = io.BytesIO()
df.to_excel(buf, index=False, sheet_name="stock")
buf.seek(0)
print(pd.read_excel(buf, sheet_name="stock"))

# Output:
#   item  qty
# 0  pen   10
# 1  ink    3
Related Topics
Common Mistakes
  1. Missing the openpyxl dependency
  2. Forgetting sheet_name
  3. Writing the index by accident
Chapter Summary
  • Excel needs openpyxl
  • sheet_name picks the sheet
  • ExcelWriter writes multiple sheets
  • index=False skips the index
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.