Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Openpyxl: set background color to a row and column Attribute Error

having looked at a few examples over here I tried to set background color to an entire row and column. I have done

 import openpyxl
 from openpyxl.styles import PatternFill
 wb = openpyxl.load_workbook(self.inputfile)
 ws = wb.active
 ws['A1'].fill = PatternFill(bgColor="FFC7CE", fill_type = "solid")`

I get an Attribute error if I do `ws[1].fill =PatternFill(bgColor="FFC7CE", fill_type = "solid")

The above code fills a single cell(A1). But how do I go forward if I want to fill an entire row(1), and an entire column(A).

like image 632
Zedak Avatar asked Dec 06 '22 15:12

Zedak


1 Answers

Iterates all columns, starting at the Column specified in the min_col=1 argument.
Ends after one row, as the row arguments min_row=1 and max_row=1 are equal.
Arguments min_row/max_row can point to any row, even also outside data.

  for rows in ws.iter_rows(min_row=1, max_row=1, min_col=1):
    for cell in rows:
      cell.fill = PatternFill(bgColor="FFC7CE", fill_type = "solid")

For entire Column, use:

iter_cols(min_col=None, max_col=None, min_row=None, max_row=None)

If you only give min_* attribute values, max row/column are used.

Tested with Python:3.4.2 - openpyxl:2.4.1

like image 169
stovfl Avatar answered Apr 18 '23 08:04

stovfl