openpyxl get sheet by name

horace_vr picture horace_vr · Apr 23, 2016 · Viewed 89.3k times · Source

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

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...)?

Answer

Valeriy Solovyov picture Valeriy Solovyov · Apr 23, 2016

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']