我尝试了https://xlsxwriter.readthedocs.io/format.html中所有可以想象的组合,并且发现了与堆栈溢出有关的所有答案。
99.99%的机会很简单,因为这些通常是我死胡同的原因。
我要在第一张工作表中编写摘要,并遍历df的字典以将多个df写到单独的工作表中(这很好)
我可以将数字格式应用于摘要,但不能在循环中使用。
writer = ExcelWriter('Players ' + str(date.datetime.now().strftime("%d-%m-%Y %H;%M;%S")) +'.xlsx', engine='xlsxwriter')
summary.to_excel(writer,'Summary',index=False)
workbook = writer.book
worksheet = writer.sheets['Summary']
format1 = workbook.add_format({'num_format': '0.000'})
worksheet.set_column('A:A', 15)
worksheet.set_column('B:B', 15)
worksheet.set_column('C:C', 6, format1)
worksheet.set_column('D:D', 15)
worksheet.conditional_format('C2:C100', {'type': '3_color_scale',
'min_color': "green",
'mid_color': "yellow",
'max_color': "red"})
#Above works
#below doesn't format
#loop through summary and players individual tables
#write an individual table to excel if score > 0
for index, row in summary.iterrows():
for tbl in player_df_dict:
if (row['Player_1'] == tbl[0]) & (row['Player_2'] == tbl[1]) & (row['Score']>0):
player_df_dict[tbl].to_excel(writer,str(tbl[0])+" and "+str(tbl[1]),index=False, columns=cols)
worksheet = writer.sheets[str(tbl[0])+" and "+str(tbl[1])]
#format2 = workbook.add_format({'num_format': '0.000'})
#worksheet.set_column('D:D', 20, format1)
#worksheet.set_column('D:D', 20, format2)
writer.save()
我尝试过:
答案 0 :(得分:2)
您没有完全显示mcve
我所能告诉你的是,设置列是有效的。我也以两种略有不同的方式来执行此操作(您+使用writer.sheets[tabname]
,即没有为工作表创建显式变量。
在下面的示例中,两种情况都将应用格式设置。
此外,在循环之外定义格式-这是书的属性,而不是图纸的属性。
下面的代码创建一个随机浮点数据框,将其导出到excel并格式化B和C列-请记住,Python的第0列是A列)
import numpy as np
import pandas as pd
writer =pd.ExcelWriter('xlsx_test.xlsx')
format_1 = writer.book.add_format({'num_format': '0.000'})
for i in range(3):
tabname = str(i)
pd.DataFrame(np.random.rand(10,4) ).to_excel(writer, tabname)
writer.sheets[tabname].set_column(1,2, None, format_1)
for i in ["a","b"]:
tabname = i
pd.DataFrame(np.random.rand(10,4) ).to_excel(writer, tabname)
ws = writer.sheets[i]
ws.set_column(1,2, None, format_1)
writer.close()