openpyxl按名称获取表格

时间:2016-04-23 17:22:38

标签: python openpyxl

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

wb = load_workbook(filename)
active_ws = wb.active

而不是wb.active,我怎么能说Sheets('Data')之类的东西(这就是VBA语法的样子......)?

2 个答案:

答案 0 :(得分:35)

您应该使用wb[sheetname]

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

PS: 您应该检查工作表名称wb.sheetnames

中的工作表
print(wb2.sheetnames)
['Sheet2', 'New Title', 'Sheet1']

答案 1 :(得分:1)

import openpyxl

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

参考: How to switch between sheets in excel openpyxl python to make changes