Get sheet by name using openpyxl

Question:

I am writing some data into an Excel file, but I don’t know how to adjust the code in order to be able to control which sheet I am writing into:

from openpyxl import load_workbook

wb = load_workbook(filename)
active_ws = wb.active

Instead of wb.active, how can I say something like Sheets('Data') (this is how the VBA syntax would look like…)?

Asked By: horace_vr

||

Answers:

You should use wb[sheetname]

from openpyxl import load_workbook
wb2 = load_workbook('test.xlsx')
ws4 = wb2["New Title"]

PS:
You should check if your sheet in sheet names wb.sheetnames

print(wb2.sheetnames)
['Sheet2', 'New Title', 'Sheet1']
Answered By: Valeriy Solovyov
import openpyxl

n = 0
wb = openpyxl.load_workbook('D:excel.xlsx')
sheets = wb.sheetnames
ws = wb[sheets[n]]

The reference:
How to switch between sheets in Excel openpyxl Python to make changes

Answered By: Youssri Abo Elseod

Fix your openpyxl version. Upgrading from 2.3.2 to 2.4.10 will fix this issue. Do this:

pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org openpyxl==2.4.10
Answered By: Aarthi Rishi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.