[英]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')
After that I need to find a way that allows me to map each worksheet in wb1
to the name of the worksheet.之后,我需要找到一种方法,允许我将
wb1
中的每个工作表映射到工作表的名称。 So the end product should be something like ws1 = [name of sheet 1], ws2 = [name of sheet 2], and so on.所以最终产品应该类似于 ws1 = [工作表 1 的名称]、ws2 = [工作表 2 的名称],等等。
for sheet in wb1:
sheet.title = wb1[sheet.title]
This does not work – it doesn't put a str
around it and moreover it give the type error:这是行不通的——它没有在它周围加上一个
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
How should I do it?我该怎么做?
You probably wanted this:你可能想要这个:
for num, sheet in enumerate(wb1, 1):
vars()["ws{}".format(num)] = sheet.title
To construct the names ws1
, ws2
, ..., we use the .format()
method to append the string representation of the num
number to the "ws"
string.为了构造名称
ws1
、 ws2
、 ...,我们使用.format()
方法将num
数字的字符串表示附加到"ws"
字符串。
To (indirectly) create variables with those names, we add them as keys to the vars()
dictionary.为了(间接)创建具有这些名称的变量,我们将它们作为键添加到
vars()
字典中。
(The built-in function vars()
will give you the updatable dictionary of all used names, so you may add new items to them. (内置函数
vars()
将为您提供所有已使用名称的可更新字典,因此您可以向它们添加新项目。
The built-in function enumerate()
will give you something as list of pairs (1, worksheet1)
, (2, worksheet2)
, and so on.)内置函数
enumerate()
会给你一些东西作为对列表(1, worksheet1)
, (2, worksheet2)
,等等。)
Better than create new names in your for
loop is to create a list of names, eg比在
for
循环中创建新名称更好的是创建名称列表,例如
ws = [sheet.title for sheet in wb1]
(and the access them with index: ws[0]
, ws[1]
, and so on). (以及使用索引访问它们:
ws[0]
、 ws[1]
等等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.