horace_vr horace_vr - 7 months ago 31
Python Question

Python openpyxl select sheet

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

You should use .get_sheet_by_name

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

PS: You should check if your sheet in sheet names .get_sheet_names()

print wb2.get_sheet_names()
>>> print(wb2.get_sheet_names())
['Sheet2', 'New Title', 'Sheet1']