我有一个 Python 脚本,它迭代一组 Excel 命名范围(DT_1、DT_2、... DT_30)。所有范围都位于同一工作簿、同一张工作表中,并且都进行了系统命名。该脚本将每个范围保存为 jpeg,文件名为“DT_1”、“DT_2”等,全部放在一个文件夹中。有 30 个命名范围。当脚本到达 DT_25 时,它会抛出 KeyError:DT_25。
Python代码:
import matplotlib.pyplot as plt
import openpyxl
wb = openpyxl.load_workbook('C:\\Users\\barry\\Desktop\\WS_Generators\
\Stats_WS_Generator_2024 TEST.xlsm', data_only=True)
for i in range(30):
named_range = wb.defined_names['DT_' + str(i+1)]
cells = named_range.destinations
# Get the first (and only) cell range
sheet_name, cell_range = next(cells)
sheet = wb[sheet_name]
data = [[cell.value for cell in row] for row in sheet[cell_range]]
# Create a figure and axis
fig, ax = plt.subplots(figsize = (3,3), dpi = 400)
fig.canvas.draw()
# Hide axes
ax.axis('off')
# Create table
table = ax.table(cellText=data, loc='center', cellLoc='center')
# Set table properties
table.auto_set_font_size(False)
table.set_fontsize(11)
table.scale(1, 1.5)
# Add borders and decrease white space with bbox
for cell in table._cells:
table._cells[cell].set_edgecolor('black')
table._cells[cell].set_linewidth(0.5)
bbox = table.get_window_extent(fig.canvas.get_renderer())
bbox = bbox.from_extents(bbox.xmin-25, bbox.ymin-25, bbox.xmax+25, bbox.ymax+25)
bbox_inches = bbox.transformed(fig.dpi_scale_trans.inverted())
#Show the table
#plt.show()
plt.savefig("C:\\Users\\barry\\Desktop\\WS_Generators\\TempImage\\DT_" + str(i+1) + ".jpg", bbox_inches=bbox_inches, pad_inches = 0.1)
plt.close()
我已经查遍了一切,包括SO,但什么也没有。在此程序的先前版本中,我使用了 24 个命名范围,但出现了 KeyError:DT_24。这是回溯:
Traceback (most recent call last):
File ~\anaconda3\Lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec
exec(code, globals, locals)
File c:\users\barry\.spyder-py3\python code useful for worksheet generators\table -
create table image from excel named range and save several images test01.py:19
named_range = wb.defined_names['DT_' + str(i+1)]
KeyError: 'DT_25'
保存 jpg 的临时文件夹完全按照要求包含前 24 个 jpg。每个 jpg 大约 50 KB。我已经仔细检查过范围 DT_25 确实存在,并且它的命名与其他所有范围一样。它是一个 2x5 的数字矩阵,与其他命名范围没有什么不同。
这是本工作簿中每个命名范围的屏幕截图。当我用 python 检查长度时,siad 字典中有 25 个项目。
我很尴尬。自从我添加范围“DT_25”到“DT_30”以来,工作簿尚未保存。保存后,Python 代码就完美运行了。简单,简单的监督。 @moken 和 @user202311 感谢您的帮助和建议。