openpyxl get sheet by name

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

wb = load_workbook(filename) active_ws = wb.active 

Instead of wb.active , how can I say something like Sheets('Data') (this will be the syntax of VBA ...)?

+15
source share
2 answers

You must use wb[sheetname]

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

PS: You need to check if your sheet matches the sheet names wb.sheetnames

 print(wb2.sheetnames) ['Sheet2', 'New Title', 'Sheet1'] 
+37
source
 import openpyxl n = 0 wb = openpyxl.load_workbook('D:\excel.xlsx') sheets = wb.sheetnames ws = wb[sheets[n]] 

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

+1
source

Source: https://habr.com/ru/post/1247782/


All Articles