user3782604
user3782604

Reputation: 330

Python: xlsxwriter highlight cells by range without condition

I have a dataframe with 3 columns. I like to highlight column a as orange, column b as green, column c as yellow but controlled by end of row.

using xlsxwriter I found examples for highlighting the entire column with ".add_format" but I didn't want the entire column to be highlighted.

How can I use xlsxwriter to highlight specific cells without using ".conditional_format"?

df = {'a': ['','',''],
       'b':[1,2,2]
       'c':[1,2,2]}

Upvotes: 1

Views: 1737

Answers (1)

Dimitris Thomas
Dimitris Thomas

Reputation: 1393

With xlsxwriter i am applying format using 2 different ways. Mainly with the function set_column (if you don't mind the format expanding until the end of the file) and using for loops if i do not want the format to expand until the end of the file (for example borderlines and background colors).

So this is how you can apply format to your dataframe:

import pandas as pd

# Create a test df
data = {'a': ['','',''], 'b': [1,2,2], 'c': [1,2,2]}
df = pd.DataFrame(data)

# Import the file through xlsxwriter
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Define the formats
format_orange = workbook.add_format({'bg_color': 'orange'})
format_green = workbook.add_format({'bg_color': 'green'})
format_bold = workbook.add_format({'bold': True, 'align': 'center'})

# Start iterating through the columns and the rows to apply the format
for row in range(df.shape[0]):
    worksheet.write(row+1, 0, df.iloc[row,0], format_orange)

# Alternative syntax
#for row in range(df.shape[0]):
#   worksheet.write(f'A{row+2}', df.iloc[row,0], format_orange)

for row in range(df.shape[0]):
    worksheet.write(row+1, 1, df.iloc[row,1], format_green)

# Here you can use the faster set_column function as you do not apply color
worksheet.set_column('C:C', 15, format_bold)

# Finally write the file
writer.save()

Output:

enter image description here

Upvotes: 3

Related Questions