piper.xl.WorkBook.add_format

WorkBook.add_format(worksheet=None, column_attr=None)[source]

Add worksheet column format (rule)

Parameters
  • worksheet – worksheet object reference

  • column_attr

    column attribute(s) to apply (dict or list)

    You can pass a dictionary containing a single format change or, pass a list of dictionary format definitions.

    Pass the following ‘keywords’, ‘column’, ‘width’, ‘format’

    for list of formats or styles, type wb.get_styles()

Examples

# Set individual columnar format
ws = wb.add_sheet(df_original, sheet_name='original', tab_color='yellow', zoom=175)

wb.add_format(ws, column_attr={'column': 'A', 'width': 10, 'format': 'center_wrap'})
wb.add_format(ws, column_attr={'column': 'B', 'width': 11})
wb.add_format(ws, column_attr={'column': 'C', 'format': 'center', 'width': 25})

# Pass a list of dictionary formats:
# Below, example to quickly set widths for a range of columns
cols = ['E', 'F', 'G', 'H', 'I']
formats = [{'column': f'{c}', 'width': 10} for c in cols]

wb.add_format(ws, column_attr=formats)

Advanced usage

# START
wb = WorkBook(f'outputs/workbook.xlsx', ts_prefix='date')

ws = wb.add_sheet(gblstprc, sheet_name='GBLSTPRC - SP, EQ', zoom=90,
                  tab_color='green', theme='Medium 16', freeze_panes='I2')
format_sheet(wb, ws)

wb.close()
# END

def format_sheet(wb, ws):
    # Center the following columns
    centered_cols = {'A': 10, 'B': 10, 'C': 6, 'D': 20, 'F': 6,
                     'H': 7, 'J': 14, 'K': 7, 'L': 7, 'M': 6, 'O':9, 'R': 7}
    for col, width in centered_cols.items():
        wb.add_format(ws, {'column': col, 'width': width, 'format': 'center'})

    wb.add_format(ws, {'column': 'Q', 'format': 'price2'})

 def format_sheet2(wb, ws):

     centred_columns = [ {'column': 'A', 'width': 12}, {'column': 'B', 'width': 7},
                         {'column': 'D', 'width': 11.29}, {'column': 'F', 'width': 9.43},
                         {'column': 'G', 'width': 20}, {'column': 'H', 'width': 9.45},
                         {'column': 'I', 'width': 9.45}, {'column': 'J', 'width': 9.14},
                         {'column': 'L', 'width': 6.71} ]

     [d.update({'format': 'center_wrap'}) for d in centred_columns]

     other_formats = [{'column': 'C', 'width': 50}, {'column': 'E', 'width': 40},
                      {'column': 'K', 'width': 95}]

     wb.add_format(ws, column_attr=centred_columns + other_formats)