Skip to content

Instantly share code, notes, and snippets.

@almugabo
Last active November 11, 2018 18:07
Show Gist options
  • Save almugabo/4babf699f56857a72f782aca16791a6f to your computer and use it in GitHub Desktop.
Save almugabo/4babf699f56857a72f782aca16791a6f to your computer and use it in GitHub Desktop.
CONDITIONAL FORMATTING in Excel with python with xlsxwriter
# CONDITIONAL FORMATTING in Excel with python
# we could use OpenPyXL or xlsxwriter
# Here we use xlsxwriter
#https://xlsxwriter.readthedocs.io/working_with_conditional_formats.html
#https://xlsxwriter.readthedocs.io/example_conditional_format.html#ex-cond-format
import pandas as pd
import xlsxwriter
# Create a Pandas dataframe from some data.
df_1 = pd.DataFrame({'var_1': [10, 20, 30, 20, 15, 30, 45],
'var_2': [1, 2, 3, 0, 5, 3, 4]})
df_2 = pd.DataFrame({'var_1': [10, 20, 30, 20, 15, 30, 45],
'var_2': [8, 7, 3, 0, 5, 25, 4],
'var_3': [80, 70, 30, 10, 15, 95, 84]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
xWriter = pd.ExcelWriter('xtest_2.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
# Firts table
df_1.to_excel(excel_writer = xWriter,
sheet_name='Sheet1',
na_rep='',
float_format=None,
columns=None,
header=True,
index=False, # important parameters
index_label=None,
startrow=0, # placing the table
startcol=0,
engine=None,
merge_cells=True,
encoding=None,
inf_rep='inf',
verbose=True,
freeze_panes=None)
# Second table
df_2.to_excel(excel_writer = xWriter,
sheet_name='Sheet1',
na_rep='',
float_format=None,
columns=None,
header=True,
index=False, # important parameters
index_label=None,
startrow=0, # placing the table
startcol=3,
engine=None,
merge_cells=True,
encoding=None,
inf_rep='inf',
verbose=True,
freeze_panes=None)
# Workbook ansprechen : Get the xlsxwriter objects from the dataframe writer object.
xWB = xWriter.book
xWSheet = xWB.get_worksheet_by_name('Sheet1')
# apply conditional formating
# First Table
xWSheet.conditional_format('A2:B8', {'type': 'data_bar',
'bar_solid': True,
'bar_color': '#63C384'}
)
# Second table
xWSheet.conditional_format('D2:E8', {'type': '3_color_scale'})
# add sparklines : DO NOT SHOW IN LIBRE OFFICE !!!!!!!!
xWSheet.add_sparkline('H2', {'range': 'D2:D9','weight': 0.25})
xWSheet.add_sparkline('H3', {'range': 'E2:E9','weight': 0.25})
xWSheet.add_sparkline('H4', {'range': 'F2:F9','weight': 0.25})
# save
xWriter.save()
print('OK')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment