这是有关错误原因的一些其他信息,可能对您有所帮助.
ValueError:"Table with name Membership already exists"是在Openpyxl工作表文件的'add_table()'函数中生成的.
即错误文本只存在于该函数中,因此只有在调用该函数时才会出现.
当您在代码中将表添加到工作表时调用此函数'add_table()',例如,创建表‘Table1’,然后添加到工作表VBS_Membership_ws.table_add(TABLE1)
.
但是,如果工作簿包含至少具有一个表的任何工作表,它也将由load_workbook
调用.
在"Load_Workbook"上,代码将判断工作簿中的每个工作表,如果存在表,则 for each 工作表调用ws.add_table(table)
,其中TABLE是该表的名称.
这就是在代码行VBS_Metrics_Report = openpyxl.load_workbook(os.path.join(VBS_Metrics_Report_dir, "VBS_Metrics_Report.xlsx"))
上产生错误的原因
调用‘ADD_TABLE’时,它将运行重复的表名判断,如果返回True,则引发ValueError.
Worksheet.py
def add_table(self, table):
...
if self.parent._duplicate_name(table.name):
raise ValueError("Table with name {0} already exists".format(table.name))
在_DUPLICATE_NAME函数中,测试很简单;
Workbook.py
if name == t.lower():
where
'name' is the name of the table to be checked
't' is the name of an existing table
Both 'name' and 't' are set to lowercase so that the check is case insensitive.
There is no check here against the Sheet Name (Title) so having a Table with the same name as the Sheet will not return True and raise the error.
"t"列表在中显示为累积,因 for each 表名都被选中,它被添加到"t"列表以对照下一个表名进行判断.
例如;
如果我在名为‘Table1’、‘Table2’和‘Table3’的工作表上有3个表,那么
- "Table1";%t为空,因此不对照任何内容进行判断,"Table1已添加到列表中,并且"%t"现在包含"Table1""
- "Table2";根据"Table1"进行判断,然后将"Table2"添加到列表中,因此"t"现在包含"Table1"和"Table2"
- 'Table3'; Is checked against 'Table1' and 'Table2'
Note the 't' list cumulation will be across all sheets since the unique naming is across the workbook. So if there was another Sheet with a table then 't' would contain the three table names for the next Sheet where the first table would be checked against 'Table1', 'Table2' and 'Table3'.
Therefore I can only see the error occurring if in fact two tables are named the same which is not possible to create in Excel or in Openpyxl given this check. However if the Excel file is manually modified or using an app that does not check names before updating perhaps this might happen.
However ultimately as mentioned without the actual workbook itself it's difficult to determine exactly what is happening but you can debug the code yourself to see what is occurring at these points.