Xlsxwriter:在同一工作表中格式化三个单元格区域

时间:2016-03-16 06:13:12

标签: python pandas xlsxwriter

我想将A1:E14格式化为美元,F1:K14格式为百分比,A15:Z1000格式为美元。有没有办法在XlsxWriter中执行此操作?

我知道如何将完整列格式化为美元/百分比,但我不知道如何格式化部分列 - 无论我上次做什么都会覆盖列F:K

数据从大熊猫开始,很高兴解决那里的问题。以下似乎不起作用:

sheet.set_column('A1:E14', None, money_format)

更多代码:

with pd.ExcelWriter(write_path) as writer:
    book = writer.book
    money_fmt = book.add_format({'num_format': '$#,##0'})
    pct_fmt = book.add_format({'num_format': '0.00%'})
    # call func that creates a worksheet  named total with no format
    df.to_excel(writer, sheet_name='Total', startrow=0)
    other_df.to_excel(writer, sheet_name='Total', startrow=15)
    writer.sheets['Total'].set_column('A1:E14',20, money_fmt)
    writer.sheets['Total'].set_column('F1:K14',20, pct_fmt)
    writer.sheets['Total'].set_column('F15:Z1000', 20, money_fmt)

1 个答案:

答案 0 :(得分:1)

我看不到使用Pandas xlsxwriter实现每格格式化的方法,但可以使用openpyxl在单独的步骤中应用格式,如下所示:

import openpyxl

def write_format(ws, cell_range, format):
    for row in ws[cell_range]:
        for cell in row:
            cell.number_format = format

sheet_name = "Total"

with pd.ExcelWriter(write_path) as writer:
    write_worksheet(df, writer, sheet_name=sheet_name)  

wb = openpyxl.load_workbook(write_path)
ws = wb.get_sheet_by_name(sheet_name)   

money_fmt = '$#,##0_-'
pct_fmt = '0.00%'

write_format(ws, 'A1:G1', money_fmt)
write_format(ws, 'A1:E14', money_fmt)
write_format(ws, 'F1:K14', pct_fmt)
write_format(ws, 'F15:Z1000', money_fmt)    

wb.save(write_path) 

尝试使用xlsxwriter时,它始终会覆盖Pandas中的现有数据。但是,如果Pandas随后重新编写数据,则会覆盖任何应用的格式。似乎没有任何方法可以在不覆盖内容的情况下将格式应用于现有单元格。例如,write_blank()函数声明:

  

此方法用于向不包含的单元格添加格式   字符串或数字值。