我注释掉了与我的问题无关的代码。
'
header_format = ws.cell(row = 1, column = 1)
--num_rows = ws.max_row
--totals_row = ws.max_row + 1
--ws.insert_rows(idx=0)
--ws.merge_cells(report_title_cell)
with header_format as h:
h.value = report_title + str(month) + ' - ' + str(year)
h.fill = PatternFill(patternType="solid", fgColor='00C0C0C0', bgColor='00C0C0C0')
h.alignment = Alignment(horizontal='center')
h.font = Font(bold='true', name='arial',size='16')
在此之前我有一些代码,我只是直接引用单元格并逐行格式化。我试图清理代码,这样就没有冗余了。
您的代码示例中有许多行会给您带来错误。
正如 @BigBen 所说,您的代码示例应该执行并产生您正在查询的问题。不要引入许多其他错误,以免其他人猜测您要问的是哪一个。
按理说,您至少会提及错误是什么,这样我们就可以确定我们正在查看同一件事。
我希望最后一个问题就是您要问的问题,但我会列出我看到的代码中的错误。
--num_rows = ws.max_row
--totals_row = ws.max_row + 1
'report_title'、'month'、'year' 未定义。
'header_format' 是一个 Cell 对象。它不是上下文管理器,因此不能用作上下文管理器。
with header_format as h:
会返回属性错误,没有进入(或退出)方法
实际上你在这里所做的就是
h = header_format
h.value = report_title + str(month) + ' - ' + str(year)
h.fill = PatternFill(patternType="solid", fgColor='00C0C0C0', bgColor='00C0C0C0')
h.alignment = Alignment(horizontal='center')
h.font = Font(bold='true', name='arial', size='16')
这里不需要 CM。使用此对象不会出现内存泄漏或僵尸进程问题。
阅读 Python 中的上下文管理器