我应该如何将每个工作表分配给它自己的变量?
How should I assign each worksheet to its own variable?
from openpyxl import *
#wb1 is the unallocated pupils
wb1 = load_workbook('unallocated.xlsx')
#wb2 will be the final allocations
wb2 = Workbook()
wb2.save("allocations.xlsx")
wb2 = load_workbook('allocations.xlsx')
之后,我需要找到一种方法,让我可以将 wb1
中的每个作品 sheet 映射到作品的名称 sheet。因此,最终产品应该类似于 ws1 = [name of sheet 1]、ws2 = [name of sheet 2],等等。
for sheet in wb1:
sheet.title = wb1[sheet.title]
这不起作用——它没有在它周围放置 str
而且它给出了类型错误:
Traceback (most recent call last):
File "C:/Users/Family guest/Desktop/CEP final project/CEP final proj.py", line 13,
in <module>
sheet.title = wb1[sheet.title]
File "C:\Users\Family guest\AppData\Local\Programs\Python\Python37\lib
\site-packages\openpyxl\workbook\child.py", line 93, in title
m = INVALID_TITLE_REGEX.search(value)
TypeError: expected string or bytes-like object
我应该怎么做?
你可能想要这个:
for num, sheet in enumerate(wb1, 1):
vars()["ws{}".format(num)] = sheet.title
要构造名称ws1
、ws2
、...,我们使用.format()
方法附加字符串表示形式num
数字到 "ws"
字符串。
为了(间接)创建具有这些名称的变量,我们将它们作为键添加到vars()
字典中。
(内置函数 vars()
将为您提供包含所有已用名称的 可更新 字典,因此您可以向其中添加新项目。
内置函数 enumerate()
将为您提供一些东西,例如对 (1, worksheet1)
、(2, worksheet2)
等的列表。)
比在 for
循环中创建新名称更好的方法是创建一个 list 名称,例如。 g.
ws = [sheet.title for sheet in wb1]
(以及使用索引访问它们:ws[0]
、ws[1]
,等等)。
from openpyxl import *
#wb1 is the unallocated pupils
wb1 = load_workbook('unallocated.xlsx')
#wb2 will be the final allocations
wb2 = Workbook()
wb2.save("allocations.xlsx")
wb2 = load_workbook('allocations.xlsx')
之后,我需要找到一种方法,让我可以将 wb1
中的每个作品 sheet 映射到作品的名称 sheet。因此,最终产品应该类似于 ws1 = [name of sheet 1]、ws2 = [name of sheet 2],等等。
for sheet in wb1:
sheet.title = wb1[sheet.title]
这不起作用——它没有在它周围放置 str
而且它给出了类型错误:
Traceback (most recent call last): File "C:/Users/Family guest/Desktop/CEP final project/CEP final proj.py", line 13, in <module> sheet.title = wb1[sheet.title] File "C:\Users\Family guest\AppData\Local\Programs\Python\Python37\lib \site-packages\openpyxl\workbook\child.py", line 93, in title m = INVALID_TITLE_REGEX.search(value) TypeError: expected string or bytes-like object
我应该怎么做?
你可能想要这个:
for num, sheet in enumerate(wb1, 1):
vars()["ws{}".format(num)] = sheet.title
要构造名称ws1
、ws2
、...,我们使用.format()
方法附加字符串表示形式num
数字到 "ws"
字符串。
为了(间接)创建具有这些名称的变量,我们将它们作为键添加到vars()
字典中。
(内置函数 vars()
将为您提供包含所有已用名称的 可更新 字典,因此您可以向其中添加新项目。
内置函数 enumerate()
将为您提供一些东西,例如对 (1, worksheet1)
、(2, worksheet2)
等的列表。)
比在 for
循环中创建新名称更好的方法是创建一个 list 名称,例如。 g.
ws = [sheet.title for sheet in wb1]
(以及使用索引访问它们:ws[0]
、ws[1]
,等等)。