read_excel/to_excel
read_excel loads a worksheet from an Excel file and to_excel saves a DataFrame to one.
In this page:
Syntax
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
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
- Missing the openpyxl dependency
- Forgetting sheet_name
- 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: