Python openpyxl 按名称获取工作表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36814050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:23:20  来源:igfitidea点击:

openpyxl get sheet by name

pythonopenpyxl

提问by horace_vr

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:

我正在将一些数据写入 Excel 文件,但我不知道如何调整代码以便能够控制我正在写入的工作表:

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

而不是wb.active,我该怎么说Sheets('Data')(这是 VBA 语法的样子......)?

回答by Valeriy Solovyov

You should use wb[sheetname]

你应该使用 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

PS:您应该检查您的工作表是否在工作表名称中 wb.sheetnames

print(wb2.sheetnames)
['Sheet2', 'New Title', 'Sheet1']

回答by Youssri Abo Elseod

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

参考: 如何在excel openpyxl python中的工作表之间切换以进行更改