简体   繁体   中英

How to give font color to a range of cells (columns and rows) in excel worksheet using openpyxl and python3?

I want to set color red to a series of cells(one column to other) in an excel sheet and using openpyxl .

I was able to find how to give cells a certain color from the official documentation but I was unable to figure out how to give a range.

Basically, I want something like this using openpyxl:

inheritance_cell_format = wb.add_format()
inheritance_cell_format.set_font_color('red')
ws.conditional_format( 0, skip_cols-2, ws.max_row, skip_cols-1, { 'type': 'cell', 'criteria': '=', 'value': '⇒', 'format': inheritance_cell_format } )

The above snippet works in xlsxwriter.

As of now, obviously, I am getting an error on the first line stating that workbook doesn't have an attribute ' add_format() '

You can color a range with a loop using the method .iter_rows() or iter_cols(). You could import PatternFill to color it.

import openpyxl as px
from openpyxl.styles import PatternFill

wb = px.load_workbook(file) #imports file
ws = wb.active #Active sheet (first one)
for row in sheet.iter_rows(min_row=1, max_col=3, max_row=2): #max row and col (range)
   for cell in row:
       cell.fill = PatternFill(start_color="FF0000", fill_type = "solid") #html colors


wb.save(file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM