openpyxl get sheet by name

那年仲夏 提交于 2019-11-26 20:38:12

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/36814050/openpyxl-get-sheet-by-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!