【发布时间】:2019-06-24 13:23:54
【问题描述】:
我正在尝试使用 python 脚本自动扩展 Excel 文件,但它会引发一些错误。在这里请求您的帮助。
我已尝试使用以下代码。
import openpyxl
from string import ascii_uppercase
newFile = "C:\\Users\\subhendu.a.panda\\Documents\\Details.xlsx"
wb = openpyxl.load_workbook(filename = newFile)
worksheet = wb.active
for col in worksheet.columns:
max_length = 0
column = col[0].column # Get the column name
for cell in col:
if cell.coordinate in worksheet.merged_cells: # not check merge_cells
continue
try: # Necessary to avoid error on empty cells
if len(str(cell.value)) > max_length:
max_length = len(cell.value)
except:
pass
adjusted_width = (max_length + 2) * 1.2
worksheet.column_dimensions[column].width = adjusted_width
wb.save(newFile)
它抛出以下错误:
Traceback(最近一次调用最后一次): 文件“C:/Users/subhendu.a.panda/Desktop/myvenv/myV/expandExcel.py”,第 21 行,在 worksheet.column_dimensions[column].width =adjusted_width getitem 中的文件“C:\Users\subhendu.a.panda\Desktop\myvenv\myV\lib\site-packages\openpyxl\utils\bound_dictionary.py”,第 26 行 setattr(值,self.reference,键) set 中的文件“C:\Users\subhendu.a.panda\Desktop\myvenv\myV\lib\site-packages\openpyxl\descriptors\base.py”,第 44 行 raise TypeError('expected' + str(self.expected_type)) 类型错误:预期
【问题讨论】:
-
异常看起来不完整。
-
异常详情:expandExcel.py",第 21 行,在
worksheet.column_dimensions[column].width =adjusted_width -
Excption 2 : openpyxl\utils\bound_dictionary.py",第 26 行,在 getitem setattr(value, self.reference, key) .... 代码: def __getitem__(self, key): value = super(BoundDictionary, self).__getitem__(key) 如果 self.reference 不是 None: setattr(value, self.reference, key) 返回值
-
异常 3 : openpyxl\descriptors\base.py",第 44 行,在 set raise TypeError('expected ' + str(self.expected_type)) 违反代码:: def __set__(self, instance, value): if not isinstance(value, self.expected_type): if (not self.allow_none or (self.allow_none and value is not None)): raise TypeError('expected ' + str (self.expected_type)) super(Typed, self).__set__(instance, value)
标签: python-3.x python-2.7 openpyxl