使用pandas.ExcelWriter()和engine = openpyxl保留条件格式

我试图从一个模板文件,包含条件格式的单元格范围,我将填充数据创build一堆excel文件。

我从一个excel文件创build一个数据框,其中包含了一个描述机场的一堆数据列的状态下的所有机场。 然后,我想为每个机场提供一个摘要文件,这个文件基本上是提取机场的行,并将其作为列添加到新的excel文件中,并附加一些列。 目前这一切正在工作。

但是,当我将数据框写入从模板excel文件创build的新文件时,新文件中的所有内容都被保留(其他填充的单元格仍然存在),除非条件格式不显示。 当我查看新文件中的条件格式规则时,规则在那里,但是格式部分被重置。 见下图:

模板文件格式: 模板文件格式](边框存在)

在新文件中格式化(从模板复制并从数据框填充): 在新文件中格式化](无边框)

所以这是代码:

创build输出文件名,复制模板并用新名称保存:

# ap is the single airport row extracted from the master frame (series here) ap_name = ap['Airport Name'].replace('/', '-').strip() ap_id = ap['Airport Identifier'] file_name = '{} ({}).xlsx'.format(ap_name, ap_id) output_ap_file = path.join(output_folder, file_name) shutil.copy(input_template_file, output_ap_file) # copy template and create new file 

注意:如果我查看在上一步中创build的文件,格式正常工作。 我可以添加我的触发器单元格和行边框添加

清理新的机场系列,并把它作为一个数据框与其他cols:

 ap = ap.dropna() ap.name = 'Existing Data' ap = ap.reset_index().rename(columns={'index': 'Information'}) ap.insert(len(ap.columns), 'Current Information?', np.nan) ap.insert(len(ap.columns), 'Corrected Information', np.nan) 

定义一个作者,并将数据框写入新文件:

 writer = pd.ExcelWriter(output_ap_file, engine='openpyxl') book = load_workbook(output_ap_file) writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) ap.to_excel(writer, index=False, startrow=start_row) writer.save() 

如前所述,新文件从模板文件成功保留了现有的单元格,在正确的范围内填充了数据,甚至保留了条件格式化的规则,但规则中的实际格式被重置。

有点损失,任何帮助表示赞赏。

谢谢!