How to apply multiple formats to one column with XlsxWriter
Asked Answered
P

2

8

In the below code I apply number formatting to each of the columns in my excel sheet. However, I can't seem to figure out to apply multiple formattings to a specific column, either the centering or the numbering end up being over written. Is it even possible to apply two types of formatting to one column?

def to_excel(video_report):

    # Create a Pandas Excel writer using XlsxWriter as the engine.
    writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

    # Convert the dataframe to an XlsxWriter Excel object.
    video_report.to_excel(writer, sheet_name='Sheet1', na_rep="-")

    # Get the xlsxwriter objects from the dataframe writer object.
    workbook  = writer.book
    worksheet = writer.sheets['Sheet1']

    # Add some cell formats.
    integer = workbook.add_format({'num_format': '0'})
    decimal = workbook.add_format({'num_format': '0.00'})
    percentage = workbook.add_format({'num_format': '0.0%'})
    center = workbook.add_format({'align': 'center'})

    # APPLY CENTERING
    worksheet.set_column('B:L', None, center)

    # APPLY NUMBER FORMATTING   
    worksheet.set_column('B:B', 13, integer )
    worksheet.set_column('C:C', 17, percentage )
    worksheet.set_column('D:D', 19, percentage )
    worksheet.set_column('E:E', 15, integer )
    worksheet.set_column('F:F', 15, percentage )
    worksheet.set_column('G:G', 15, decimal )
    worksheet.set_column('H:H', 13, integer )
    worksheet.set_column('I:I', 13, integer )
    worksheet.set_column('J:J', 13, integer )
    worksheet.set_column('K:K', 13, integer )
    worksheet.set_column('L:L', 13, integer )


    writer.save()

to_excel(video_report)
Preeminent answered 1/6, 2015 at 2:5 Comment(0)
G
11

Is it even possible to apply two types of formatting to one column?

Yes. By adding the two or more properties to the format object that you are using. For example:

integer = workbook.add_format({'num_format': '0', 'align': 'center'})

See the XlsxWriter docs on how to use formats.

Gorgeous answered 1/6, 2015 at 10:14 Comment(0)
S
6

While jmcnamara best answers the question, you can also define a new format object. Alternative example:

header = workbook.add_format({'align': 'center'})
        header.set_bold()
        header.set_italic()
        header.set_underline()

worksheet.write(0, col_hdr, key, header)
Stratosphere answered 4/6, 2015 at 19:38 Comment(1)
Any chance you know how to answer this: #30576998?Preeminent

© 2022 - 2024 — McMap. All rights reserved.