Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to apply cell style when using `append` in openpyxl?

I am using openpyxl to create an Excel worksheet. I want to apply styles when I insert the data. The trouble is that the append method takes a list of data and automatically inserts them to cells. I cannot seem to specify a font to apply to this operation.

I can go back and apply a style to individual cells after-the-fact, but this requires overhead to find out how many data points were in the list, and which row I am currently appending to. Is there an easier way?

This illustrative code shows what I would like to do:

def create_xlsx(self, header):
    self.ft_base = Font(name='Calibri', size=10)
    self.ft_bold = self.ft_base.copy(bold=True)
    if header:
        self.ws.append(header, font=ft_bold) # cannot apply style during append
like image 668
Roberto Avatar asked Mar 20 '15 17:03

Roberto


1 Answers

ws.append() is designed for appending rows of data easily. It does, however, also allow you to include placeless cells within a row so that you can apply formatting while adding data. This is primarily of interest when using write_only=True but will work for normal workbooks.

Your code would look something like:

data = [1, 3, 4, 9, 10]


def styled_cells(data):
    for c in data:
       if c == 1:
            c = Cell(ws, column="A", row=1, value=c)
            c.font = Font(bold=True)
       yield c

ws.append(styled_cells(data))

openpyxl will correct the coordinates of such cells.

like image 58
Charlie Clark Avatar answered Sep 28 '22 01:09

Charlie Clark