简体   繁体   中英

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

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

Fix your openpyxl version. Do this:

pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org openpyxl==2.4.10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM