【问题标题】:Pandas fromat column multiple sheets熊猫格式列多张
【发布时间】:2017-09-11 13:32:02
【问题描述】:

使用以下代码,我设法为每个国家/地区创建 excel 文件,但我无法格式化 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)

我需要为每个创建的文件的 3 张工作表中的每一个格式化列 B:F

【问题讨论】:

  • 检查XlsxWriter examples - 在该页面上查找set_column()...
  • 添加了这个但不起作用:worksheet.set_column('A:H', format2)

标签: python excel pandas xlsxwriter


【解决方案1】:

您可以set custom format到每个工作表:

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()

还有更动态的解决方案:

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()

【讨论】:

    猜你喜欢
    • 2020-06-17
    • 2015-07-08
    • 1970-01-01
    • 2018-06-05
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    相关资源
    最近更新 更多