我使用下面的代码来更新 Excel (.xlsm) 文件,并将其中的一些值复制到同一文件中的其他位置。这里我使用两个函数从一个位置复制和粘贴一些所需的单元格范围到另一个并想要复制具有完整字体和边界的单元格
我的代码看起来像 -
wb=load_workbook('Excel.xlsm',read_only=False,keep_vba=True)
ws=wb['K0 Reg Patch Util']
def copyRange(startCol,startRow,endCol,endRow,sheet):
rangeSelected=[]
fontSelected=[]
borderSelected=[]
for i in range(startRow,endRow+1,1):
rowSelected=[]
font=[]
border=[]
for j in range(startCol,endCol+1,1):
rowSelected.append(sheet.cell(row=i,column=j).value)
font.append(sheet.cell(row=i,column=j).font)
border.append(sheet.cell(row=i,column=j).border)
rangeSelected.append(rowSelected)
fontSelected.append(font)
borderSelected.append(border)
return rangeSelected,fontSelected,borderSelected
def pasteRange(startCol,startRow,endCol,endRow,sheet,copiedData,fontData,borderData):
countRow=0
for i in range(startRow,endRow+1,1):
countCol=0
for j in range(startCol,endCol+1,1):
sheet.cell(row=i,column=j).value=copiedData[countRow][countCol]
sheet.cell(row=i,column=j).font=fontData[countRow][countCol]
sheet.cell(row=i,column=j).value=borderData[countRow][countCol]
countCol+=1
countRow+=1
copiedData=[]
fontData=[]
borderData=[]
copiedData,fontData,borderData=copyRange(2,56,4,66,ws)
startC=ws.max_column+1
endC=startC+2
startR=3
endR=13
pasteRange(startC,startR,endC,endR,ws,copiedData,fontData,borderData)
wb.save('Excel.xlsm')
此后,当我运行程序时,我收到错误 -
File "ReadExcel.py", line 91, in
pasteRange(startC,startR,endC,endR,ws,copiedData,fontData,borderData)
File "ReadExcel.py", line 73, in pasteRange
sheet.cell(row=i,column=j).font=fontData[countRow][countCol]
File > "/nfs/sc/proj/skx/skx_val356/rsingh/Patch_Proj/Patch_Project_Files/GUI/VGUI/venv/lib/python3.6/site-packages/openpyxl/styles/styleable.py", line 24, in __set__
setattr(instance._style, self.key, coll.add(value))
File "/nfs/sc/proj/skx/skx_val356/rsingh/Patch_Proj/Patch_Project_Files /GUI/VGUI/venv/lib/python3.6/site-packages/openpyxl/utils/indexed_list.py", line 48, in add
self.append(value)
File "/nfs/sc/proj/skx/skx_val356/rsingh/Patch_Proj/Patch_Project_Files/GUI/VGUI/venv/lib/python3.6/site-packages/openpyxl/utils/indexed_list.py", line 43, in appendif value not in self._dict:
TypeError: unhashable type: 'StyleProxy'
有人可以指出我如何删除这个错误以及我犯了什么错误吗?我什至按照某些帖子的建议在 proxy.py 中添加了一个哈希函数。 请解决此错误
最佳答案
Question: how to remove this error and what mistake i am doing
您必须复制
样式属性。
添加并替换以下行:
from copy import copy
...
font.append(copy(sheet.cell(row=i, column=j).font))
...
border.append(copy(sheet.cell(row=i, column=j).border))
第二个 .value=borderData...
是一个拼写错误,应为:
sheet.cell(row=i,column=j).border=borderData[countRow][countCol]
您可能会收到以下错误:
IndexError: list index out of range
因为您的 ...Data
列表的维度与 pasteRange
中使用的维度不同。
原因是该行缩进错误:
return rangeSelected, fontSelected, borderSelected
您在 for
循环中的第一个循环后返回!
考虑将代码重新设计为更简单的方法。
不要先将所有数据复制到列表列表中,而是直接从单元格
复制到单元格
.
关于python - 如果值不在 self._dict : TypeError: unhashable type: 'StyleProxy' in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52226522/