pandasfromat列多张

使用下面的代码,我设法为每个国家创buildexcel文件,但我无法格式化excel列:

df=TOT.reset_index() for n, g in df.groupby('Country'): X = n.strip(" ") out_path = "C:/temp/" + n.strip(" ") + ".xlsx" C =TOTSPPerc.reset_index(level=0)[TOTSP.reset_index(level=0).Country==n].drop('Country', axis=1) B =TOTPerc.reset_index(level=0)[TOTPerc.reset_index(level=0).Country==n].drop('Country', axis=1) A= TOTcntPerc.drop('Country', axis=1) writer = pd.ExcelWriter(out_path , engine='xlsxwriter') format2 = workbook.add_format({'num_format': '0%'}) A.to_excel(writer, sheet_name="Country") B.to_excel(writer, sheet_name="Stores") C.to_excel(writer, sheet_name="SPs") writer.save() print(n) 

我需要为每个创build的文件格式化B:FB:F

您可以为每个工作表设置自定义格式 :

 for n, g in df.groupby('Country'): print (g) #your code writer = pd.ExcelWriter(out_path , engine='xlsxwriter') A.to_excel(writer, sheet_name="Country") B.to_excel(writer, sheet_name="Stores") C.to_excel(writer, sheet_name="SPs") workbook = writer.book worksheet1 = writer.sheets['Country'] worksheet2 = writer.sheets['Stores'] worksheet3 = writer.sheets['SPs'] format2 = workbook.add_format({'num_format': '0%'}) worksheet1.set_column('B:F', 18, format2) worksheet2.set_column('B:F', 18, format2) worksheet3.set_column('B:F', 18, format2) writer.save() 

而更dynamic的解决scheme:

 for n, g in df.groupby('Country'): print (g) #your code writer = pd.ExcelWriter(out_path , engine='xlsxwriter') dfs = [A,B,C] sheetnames = ['Country','Stores','SPs'] for i, df1 in enumerate(dfs): df1.to_excel(writer, sheet_name=sheetnames[i]) workbook = writer.book worksheet1 = writer.sheets[sheetnames[i]] format2 = workbook.add_format({'num_format': '0%'}) worksheet1.set_column('B:F', 18, format2) writer.save()