openpyxl get sheet by name

PythonOpenpyxl

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

import openpyxl

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

the refernce: https://stackoverflow.com/questions/45756731/how-to-switch-between-sheets-in-excel-openpyxl-python-to-make-changes?rq=1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhorace_vrView Question on Stackoverflow
Solution 1 - PythonValeriy SolovyovView Answer on Stackoverflow
Solution 2 - PythonYoussri Abo ElseodView Answer on Stackoverflow