影刀RPA Excel模板创建:标准报表模板复用 影刀RPA Excel模板创建标准报表模板复用作者林焱什么情况用什么每周生成格式一样的周报、每月生成结构一样的月报——每次从零开始搭表格太浪费时间。在影刀RPA里可以先创建一个标准模板文件然后每次只填充数据格式、公式、图表都自动继承。这比每次用代码重建格式高效得多。适用场景周报/月报/季报标准化生成、多部门统一报表格式、自动化报表分发、固定格式的数据导出。怎么做创建模板文件拼多多店群自动化报活动上架importopenpyxlfromopenpyxl.stylesimportFont,PatternFill,Alignment,Border,Side,numbersdefcreate_report_template(output_path):创建标准报表模板wbopenpyxl.Workbook()# Sheet1: 数据明细 ws_datawb.active ws_data.title数据明细# 标题行ws_data.merge_cells(A1:F1)ws_data[A1]销售数据明细报表ws_data[A1].fontFont(name微软雅黑,size16,boldTrue,colorFFFFFF)ws_data[A1].fillPatternFill(start_color1F4E79,end_color1F4E79,fill_typesolid)ws_data[A1].alignmentAlignment(horizontalcenter,verticalcenter)ws_data.row_dimensions[1].height35# 表头headers[日期,地区,产品,数量,单价,金额]forcol,headerinenumerate(headers,1):cellws_data.cell(row2,columncol,valueheader)cell.fontFont(name微软雅黑,size11,boldTrue,colorFFFFFF)cell.fillPatternFill(start_color4472C4,end_color4472C4,fill_typesolid)cell.alignmentAlignment(horizontalcenter,verticalcenter)# 预设公式行第3行到第1002行forrowinrange(3,1003):# 金额 数量 * 单价ws_data.cell(rowrow,column6).valuefIF(AND(D{row},E{row}),D{row}*E{row},)# 数字格式forrowinrange(3,1003):ws_data.cell(rowrow,column4).number_format#,##0ws_data.cell(rowrow,column5).number_format#,##0.00ws_data.cell(rowrow,column6).number_format#,##0.00# 列宽col_widths{A:12,B:10,C:20,D:10,E:12,F:14}forcol,widthincol_widths.items():ws_data.column_dimensions[col].widthwidth# Sheet2: 汇总统计 ws_summarywb.create_sheet(汇总统计)ws_summary.merge_cells(A1:C1)ws_summary[A1]汇总统计ws_summary[A1].fontFont(name微软雅黑,size14,boldTrue,colorFFFFFF)ws_summary[A1].fillPatternFill(start_color1F4E79,end_color1F4E79,fill_typesolid)ws_summary[A1].alignmentAlignment(horizontalcenter,verticalcenter)# 统计项summary_items[(总订单数,COUNTA(数据明细!C3:C1002)),(总金额,SUM(数据明细!F3:F1002)),(平均金额,IFERROR(AVERAGE(数据明细!F3:F1002),0)),(最大金额,IFERROR(MAX(数据明细!F3:F1002),0)),(最小金额,IFERROR(MIN(数据明细!F3:F1002),0)),]fori,(label,formula)inenumerate(summary_items,2):ws_summary.cell(rowi,column1,valuelabel).fontFont(name微软雅黑,size11,boldTrue)cellws_summary.cell(rowi,column2,valueformula)cell.number_format#,##0.00ifi2else#,##0ws_summary.column_dimensions[A].width15ws_summary.column_dimensions[B].width18# Sheet3: 地区分析 ws_regionwb.create_sheet(地区分析)ws_region[A1]地区ws_region[B1]订单数ws_region[C1]总金额regions[北京,上海,广州,深圳,成都,杭州]fori,regioninenumerate(regions,2):ws_region.cell(rowi,column1,valueregion)ws_region.cell(rowi,column2,valuefCOUNTIF(数据明细!B:B,A{i}))ws_region.cell(rowi,column3,valuefSUMIF(数据明细!B:B,A{i},数据明细!F:F))# 保存模板wb.save(output_path)returnoutput_path# 创建模板create_report_template(rC:\Templates\sales_report_template.xlsx)使用模板填充数据importshutilimportopenpyxlimportpandasaspddeffill_template(template_path,data_df,output_path):用模板生成报表# 1. 复制模板shutil.copy2(template_path,output_path)# 2. 打开复制的模板wbopenpyxl.load_workbook(output_path)wswb[数据明细]# 3. 填充数据从第3行开始foridx,rowindata_df.iterrows():excel_rowidx3ws.cell(rowexcel_row,column1,valuerow[日期])ws.cell(rowexcel_row,column2,valuerow[地区])ws.cell(rowexcel_row,column3,valuerow[产品])ws.cell(rowexcel_row,column4,valuerow[数量])![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/611780f8b24a40a58333c4cfcb9fde21.png#pic_center)ws.cell(rowexcel_row,column5,valuerow[单价])# 金额列有公式不用手动填# 4. 保存wb.save(output_path)returnoutput_path# 读取数据dfpd.read_excel(rC:\Data\july_sales.xlsx)dfdf[[日期,地区,产品,数量,单价]]# 用模板生成报表fill_template(template_pathrC:\Templates\sales_report_template.xlsx,data_dfdf,output_pathrC:\Reports\2026年7月销售报表.xlsx)模板版本管理importosfromdatetimeimportdatetimedefgenerate_versioned_report(template_path,data_df,output_dir,report_name):生成带版本号的报表# 确保输出目录存在os.makedirs(output_dir,exist_okTrue)# 生成带日期的文件名date_strdatetime.now().strftime(%Y%m%d_%H%M%S)filenamef{report_name}_{date_str}.xlsxoutput_pathos.path.join(output_dir,filename)# 用模板填充fill_template(template_path,data_df,output_path)returnoutput_path# 使用outputgenerate_versioned_report(template_pathrC:\Templates\sales_report_template.xlsx,data_dfdf,output_dirrC:\Reports\历史版本,report_name销售月报)多模板选择defselect_template(report_type):根据报表类型选择模板templates{daily:rC:\Templates\daily_report.xlsx,weekly:rC:\Templates\weekly_report.xlsx,monthly:rC:\Templates\monthly_report.xlsx,quarterly:rC:\Templates\quarterly_report.xlsx,}ifreport_typenotintemplates:raiseValueError(f不支持的报表类型:{report_type})![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/d32e123991284c798a05da3afba4da36.png#pic_center)ifnotos.path.exists(templates[report_type]):raiseFileNotFoundError(f模板文件不存在:{templates[report_type]})returntemplates[report_type]# 在影刀流程中# 【设置变量】report_type monthly# 【执行Python代码】选择模板并填充templateselect_template(monthly)fill_template(template,df,output_path)有什么坑坑1模板中的公式不自动计算openpyxl写入数据后模板里的公式不会自动重新计算需要在Excel中打开后才会更新# 问题填充数据后汇总统计的值还是0# 因为openpyxl不计算公式# 解决1用win32com触发计算importwin32com.client excelwin32com.client.Dispatch(Excel.Application)wbexcel.Workbooks.Open(output_path)excel.CalculateFull()# 强制重新计算所有公式![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/00613b2b84c74856befdfeeb56d1c1aa.png#pic_center)wb.Save()wb.Close()excel.Quit()# 解决2用data_onlyFalse读取在Python中算好值直接写入# 而不是依赖Excel公式坑2shutil.copy2复制后文件损坏某些情况下复制模板后文件打不开TEMU店群矩阵自动化运营核价报活动# 问题模板文件正被其他程序占用shutil.copy2(template_path,output_path)# 可能报错# 解决先关闭模板文件或用openpyxl另存![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/3dd608618be744a68e7025174f0e0466.png#pic_center)wbopenpyxl.load_workbook(template_path)wb.save(output_path)# 用openpyxl另存更安全坑3模板数据行数不够模板预设了1000行公式但实际数据有1500行# 解决动态扩展公式行defensure_formula_rows(ws,template_last_row,needed_row,formula_col6):确保公式行数足够ifneeded_rowtemplate_last_row:return# 获取模板公式template_formulaws.cell(rowtemplate_last_row,columnformula_col).value# 扩展公式forrowinrange(template_last_row1,needed_row1):# 替换行号formulatemplate_formula.replace(str(template_last_row),str(row))ws.cell(rowrow,columnformula_col).valueformula# 复制格式ws.cell(rowrow,columnformula_col).number_format#,##0.00坑4模板中的图表引用失效模板里做了图表填充数据后图表数据源不对了# openpyxl对图表的支持有限建议用win32com操作# 或者在模板中把图表数据源设为整个列如A:A而不是固定行范围# 另一个方案用Python直接生成图表不依赖模板importmatplotlib.pyplotasplt fig,axplt.subplots(figsize(8,5))df.groupby(地区)[金额].sum().plot(kindbar,axax,color#4472C4)ax.set_title(各地区销售额)ax.set_ylabel(金额元)plt.tight_layout()plt.savefig(rC:\Reports\chart.png,dpi150)# 然后把图片插入Excelwswb[地区分析]ws.add_image(openpyxl.drawing.image.Image(rC:\Reports\chart.png),E2)坑5多用户同时使用模板冲突多个影刀流程同时用同一个模板生成报表文件锁冲突# 解决每个流程先复制模板到临时目录importtempfileimportuuiddefsafe_fill_template(template_path,data_df,output_path):安全的模板填充# 复制到临时文件temp_dirtempfile.gettempdir()temp_templateos.path.join(temp_dir,ftemplate_{uuid.uuid4().hex}.xlsx)shutil.copy2(template_path,temp_template)![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/e4da127d579b4bcbadc99b62a5e964ef.png#pic_center)try:# 用临时模板填充fill_template(temp_template,data_df,output_path)finally:# 清理临时文件ifos.path.exists(temp_template):os.remove(temp_template)returnoutput_path