gpt4 book ai didi

openpyxl - 如何解决 Openpyxl TypeError : expected error in openpyxl-3. 0.3

转载 作者:行者123 更新时间:2023-12-03 21:16:04 33 4
gpt4 key购买 nike

当我从 openpyxl-2.5.12 升级到 openpyxl-3.0.3 时,我开始收到以下错误:

C:\workspace\venv_py37_64\lib\site-packages\openpyxl\descriptors\base.py", line 42, in __set__
raise TypeError('expected ' + str(self.expected_type))
TypeError: expected <class 'str'>

我该如何解决?我相信它在线上失败了:
    adjusted_width = (max_length + 2) * 1.2
worksheet.column_dimensions[column].width = adjusted_width

我目前的分辨率:
我不得不降级到 openpyxl-2.5.12 来解决现在的错误。请让我知道是否有替代解决方案或我需要对我的代码进行哪些更改才能使用最新的 openpyxl 版本。谢谢你。

这是我的完整代码片段:
def format_excel_file(excel_file_path):
"""
Formats the provided excel file - autosize, colors cell and draws thin borders
:param excel_file_path:
:return:
"""
my_name = 'format_excel_file()'

logger.info("Entered: {}".format(my_name))
excel_file_path = os.path.abspath(excel_file_path)
logger.info("Excel File: {}".format(excel_file_path))

wb = openpyxl.load_workbook(filename=excel_file_path)

fail_fill = PatternFill(start_color='f2a7a7',
end_color='f2a7a7',
fill_type='solid')

warn_fill = PatternFill(start_color='f5da71',
end_color='f5da71',
fill_type='solid')

pass_fill = PatternFill(start_color='8adb8d',
end_color='8adb8d',
fill_type='solid')

header_fill = PatternFill(start_color='46b363',
end_color='46b363',
fill_type='solid')

thin_border = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))

for worksheet in wb.worksheets:
for r, row in enumerate(worksheet.rows, start=1):
if r == 1:
for cell in row:
cell.fill = header_fill

for col in worksheet.columns:
max_length = 0
column = col[0].column # Get the column name
for cell in col:
cell.border = thin_border
if 'FAIL' in str(cell.value):
cell.fill = fail_fill
elif 'PASS' in str(cell.value):
cell.fill = pass_fill
elif 'WARN' in str(cell.value):
cell.fill = warn_fill
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 IOError as e:
print(e)
pass

adjusted_width = (max_length + 2) * 1.2
worksheet.column_dimensions[column].width = adjusted_width
wb.save(excel_file_path)
logger.info("Exited: {}".format(my_name))

最佳答案

问题是 2.6.1 中的更改,现在在设置宽度时需要列字母,而不是列号。

幸运的是,更改非常简单。改变

column = col[0].column  # Get the column name


column = col[0].column_letter  # Get the column name

关于openpyxl - 如何解决 Openpyxl TypeError : expected <class 'str' > error in openpyxl-3. 0.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60585752/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com