Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

openpyxl get sheet by name

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

like image 278
horace_vr Avatar asked Apr 23 '16 17:04

horace_vr


People also ask

How do I get the sheet name in Excel using openpyxl?

Step1: First Import the openpyxl library to the program. Step2: Load/Connect the Excel Workbook to the program. Step3: Use sheetnames property to get the names of all the sheets of the given workbook.

How do I view a specific sheet in openpyxl?

Read Specific Cells You can access their values by using dictionary-like access: sheet["A2"]. value . Alternatively, you can assign sheet["A2"] to a variable and then do something like cell. value to get the cell's value.


2 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'] 
like image 131
Valeriy Solovyov Avatar answered Sep 19 '22 08:09

Valeriy Solovyov


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

the refernce: How to switch between sheets in excel openpyxl python to make changes

like image 38
Youssri Abo Elseod Avatar answered Sep 17 '22 08:09

Youssri Abo Elseod