Закрасить ячейку excel python

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    To add color to Excel cells we will be using the Openpyxl Python Library. The Openpyxl module allows us to read and modify Excel files using Python. 

    Approach 1:

    Using the Openpyxl module, even small tasks can be done very efficiently and easily in excel.

    Input File:

    Only declare the excel name with .xlsx form if the file exists in the same folder as where the code exists. If the file exists in another folder then the linking has to be done by giving the entire path source.

    Installing the OpenPyxl module: In order to install the openpyxl module via pip run the below command in the terminal of the user’s choice:

    pip install openpyxl

    Example:

    Python3

    import openpyxl

    from openpyxl.styles import PatternFill

    wb = openpyxl.load_workbook("GFGCoursePrices.xlsx")

    ws = wb['Sheet1']

    To fill the color in the cell you have to declare the pattern type and fgColor. Now create a working sheet variable and initialize it with the current sheet you are working on using the syntax

    Python3

    colors = ['00660066', '00FFFFCC',

              '00FF0000', '0000FF00', '00660066']

    fillers = []

    for color in colors:

        temp = PatternFill(patternType='solid',

                           fgColor=color)

        fillers.append(temp)

    Here we need to keep in mind that colors value has to be strictly hex values not like ‘Blue’ ,’yellow’ , ‘red’ etc. It will not work. Otherwise, we will encounter an error like below: 

    Finally, you have to save changes using the .save() function. To fill each cell, you have to use the .fill() function depicted by the following syntax.

    Python3

    cell_ids = ['B2', 'B3', 'B4', 'B5', 'A2']

    for i in range(5):

        ws[cell_ids[i]].fill = fillers[i]

    wb.save("GFGCoursePrices.xlsx")

    Output:

    Approach 2: 

    We can also take the help of Color method of the openpyxl.styles.colors. Here we can pass integer values (0-63) and while coloring them we need to pass them as the value of a keyworded argument indexed.

    Python3

    import openpyxl

    from openpyxl.styles import PatternFill

    from openpyxl.styles.colors import Color

    wb = openpyxl.load_workbook("geeks.xlsx")

    ws = wb['Sheet1']

    colors = [6, 3, 48, 37, 28

    fillers = []

    for color in colors:

        temp = PatternFill(patternType='solid',

                           fgColor=Color(indexed=color))

        fillers.append(temp)

    cell_ids = ['B2', 'B3', 'B4', 'B5', 'A2']

    for i in range(5):

        ws[cell_ids[i]].fill = fillers[i]

    wb.save("geeks.xlsx")

    Output:

    Like Article

    Save Article

    Модуль openpyxl обеспечивает довольно гибкое управление стилями, относительно простую работу с ними. Стили в электронных таблицах XLSX используются для изменения внешнего вида данных при отображении на экране. Они также используются для определения форматирования чисел.

    Содержание:

    • Аспекты применения стилей модулем openpyxl.
    • Cтили ячеек электронной таблицы.
      • Создания нового стиля на основе другого.
      • Цвета для шрифтов, фона, границ.
      • Применение стилей.
      • Горизонтальное и вертикальное выравнивание текста.
      • Оформление границ ячеек.
      • Заливка ячеек цветом и цвет текста.
    • Именованные стили NamedStyle.
      • Создание именованного стиля.
    • Встроенные в Excel стили.

    Аспекты применения стилей модулем openpyxl.

    Стили могут быть применены к следующим аспектам:

    • font: устанавливает размер шрифта, цвет, стиль подчеркивания и т. д.
    • fill: устанавливает шаблон или градиент цвета заливки ячейки.
    • border: устанавливает стиль границы ячейки.
    • alignment: устанавливает выравнивание ячейки.

    Ниже приведены значения по умолчанию установленные модулем openpyxl:

    from openpyxl.styles import (
                            PatternFill, Border, Side, 
                            Alignment, Font, GradientFill
                            )
    
    # СТИЛЬ ШРИФТА
    font = Font(
            name='Calibri',
            size=11,
            bold=False,
            italic=False,
            vertAlign=None,
            underline='none',
            strike=False,
            color='FF000000'
                )
    
    # ЗАЛИВКА ЯЧЕЕК
    fill = PatternFill(fill_type=None, fgColor='FFFFFFFF')
    
    # ГРАНИЦЫ ЯЧЕЕК
    border = Border(
                left=Side(border_style=None, color='FF000000'),
                right=Side(border_style=None, color='FF000000'),
                top=Side(border_style=None, color='FF000000'),
                bottom=Side(border_style=None, color='FF000000'),
                diagonal=Side(border_style=None, color='FF000000'),
                diagonal_direction=0, 
                outline=Side(border_style=None, color='FF000000'),
                vertical=Side(border_style=None, color='FF000000'),
                horizontal=Side(border_style=None, color='FF000000')
                   )
    
    # ВЫРАВНИВАНИЕ В ЯЧЕЙКАХ
    alignment=Alignment(
                    horizontal='general',
                    vertical='bottom',
                    text_rotation=0,
                    wrap_text=False,
                    shrink_to_fit=False,
                    indent=0
                       )
    

    Cтили ячеек электронной таблицы.

    Существует два типа стилей: стили ячеек и именованные стили, также известные как шаблоны стилей.

    Стили ячеек являются общими для объектов, и после того, как они были назначены, их нельзя изменить. Это предотвращает нежелательные побочные эффекты, такие как изменение стиля для большого количества ячеек при изменении только одной.

    Например:

    >>> from openpyxl.styles import colors
    >>> from openpyxl.styles import Font, Color
    >>> from openpyxl import Workbook
    >>> wb = Workbook()
    >>> ws = wb.active
    >>> ws['A1'].value = 'Ячейка `A1`'
    >>> ws['D4'].value = 'Ячейка `D4`'
    # задаем стиль шрифта текста - цвет  ячейке
    >>> ft = Font(color="FF0000")
    # применяем стиль к ячейкам
    >>> ws['A1'].font = ft
    >>> ws['D4'].font = ft
    # это изменение не сработает
    >>> ws['D4'].font.italic = True 
    # Если необходимо изменить шрифт, 
    # то его необходимо переназначить новым стилем
    ws['A1'].font = Font(color="FF0000", italic=True)
    >>> wb.save('test.xlsx')
    

    Создания нового стиля на основе другого.

    Модуль openpyxl поддерживает копирование стилей.

    Пример создания нового стиля на основе другого:

    >>> from openpyxl.styles import Font
    >>> from copy import copy
    # задаем стиль
    >>> ft1 = Font(name='Arial', size=14)
    # копируем стиль
    >>> ft2 = copy(ft1)
    # а вот теперь на основе скопированного стиля 
    # можно создать новый, изменив атрибуты 
    >>> ft2.name = "Tahoma"
    # имя шрифта первого стиля
    >>> ft1.name
    # 'Arial'
    
    # имя шрифта нового стиля
    >>> ft2.name
    # 'Tahoma'
    
    # размер остался как у первого
    >>> ft2.size # copied from the
    # 14.0
    

    Цвета для шрифтов, фона, границ.

    Цвета для шрифтов, фона, границ и т.д. Можно задать тремя способами: индексированный, aRGB или тема. Индексированные цвета являются устаревшей реализацией, и сами цвета зависят от индекса, предоставленного в рабочей книге или в приложении по умолчанию. Цвета темы полезны для дополнительных оттенков цветов, но также зависят от темы, присутствующей в рабочей книге. Поэтому рекомендуется использовать цвета aRGB.

    Цвета aRGB.

    Цвета RGB устанавливаются с использованием шестнадцатеричных значений красного, зеленого и синего.

    >>> from openpyxl.styles import Font
    >>> font = Font(color="FF0000")
    

    Альфа-значение теоретически относится к прозрачности цвета, но это не относится к стилям ячеек. Значение по умолчанию 00 будет добавлено к любому простому значению RGB:

    >>> from openpyxl.styles import Font
    >>> font = Font(color="00FF00")
    >>> font.color.rgb
    # '0000FF00'
    

    Применение стилей.

    Стили применяются непосредственно к ячейкам.

    >>> from openpyxl import Workbook
    >>> from openpyxl.styles import Font, PatternFill
    >>> wb = Workbook()
    >>> ws = wb.active
    >>> c = ws['A1']
    >>> c.value = 'Ячейка `A1`'
    >>> c.font = Font(size=12)
    # можно напрямую
    >>> ws['A2'].value = 'Ячейка `A2`'
    >>> ws['A2'].font = Font(size=12, bold=True)
    >>> wb.save('test.xlsx')
    

    Стили также могут применяться к столбцам и строкам, но обратите внимание, что это относится только к ячейкам, созданным (в Excel) после закрытия файла. Если необходимо применить стили ко всем строкам и столбцам, то нужно применить стиль к каждой ячейке самостоятельно.

    Это ограничение формата файла:

    >>> col = ws.column_dimensions['A']
    >>> col.font = Font(bold=True)
    >>> row = ws.row_dimensions[1]
    >>> row.font = Font(underline="single")
    

    Горизонтальное и вертикальное выравнивание текста.

    Горизонтальное и вертикальное выравнивание в ячейках выставляется атрибутом ячейки .alignment и классом Alignment().

    Пример горизонтального выравнивания текста:

    >>> from openpyxl import Workbook
    >>> from openpyxl.styles import Alignment
    >>> wb = Workbook()
    >>> ws = wb.active
    >>> ws['A1'].value = 1500
    >>> ws['A2'].value = 1500
    >>> ws['A3'].value = 1500
    # выравниваем текст в ячейках стилями
    >>> ws['A1'].alignment = Alignment(horizontal='left')
    >>> ws['A2'].alignment = Alignment(horizontal='center')
    >>> ws['A3'].alignment = Alignment(horizontal='right')
    # сохраняем и смотрим что получилось
    >>> wb.save('test.xlsx')
    

    Вертикальное выравнивание в основном применяется когда изменена высота строки или были объединены несколько ячеек.

    Пример вертикального выравнивания данных в ячейке:

    >>> from openpyxl import Workbook
    >>> from openpyxl.styles import Alignment
    >>> wb = Workbook()
    >>> ws = wb.active
    # объединим ячейки в диапазоне `B2:E2`
    >>> ws.merge_cells('B2:E2')
    # в данном случае крайняя верхняя-левая ячейка это `B2`
    >>> megre_cell = ws['B2']
    # запишем в нее текст
    >>> megre_cell.value = 'Объединенные ячейки `B2 : E2`'
    # установить высоту строки
    >>> ws.row_dimensions[2].height = 30
    # установить ширину столбца
    >>> ws.column_dimensions['B'].width = 40
    # выравнивание текста
    >>> megre_cell.alignment = Alignment(horizontal="center", vertical="center")
    # сохраняем и смотрим что получилось
    >>> wb.save("test.xlsx")
    

    Оформление границ ячеек.

    Цвет и стиль границ/бордюров ячеек выставляется атрибутом ячейки .border и классом Border() совместно с классом Side().

    При этом аргумент стиля границ ячеек border_style может принимать ОДИН из следующих значений: ‘dashDotDot’, ‘medium’, ‘dotted’, ‘slantDashDot’, ‘thin’, ‘hair’, ‘mediumDashDotDot’, ‘dashDot’, ‘double’, ‘mediumDashed’, ‘dashed’, ‘mediumDashDot’ и ‘thick’.

    Пример стилизации границ одной ячейки:

    >>> from openpyxl import Workbook
    >>> from openpyxl.styles import Border, Side
    >>> wb = Workbook()
    >>> ws = wb.active
    >>> cell = ws['B2']
    # установить высоту строки
    >>> ws.row_dimensions[2].height = 30
    # установить ширину столбца
    >>> ws.column_dimensions['B'].width = 40
    # определим стили сторон
    >>> thins = Side(border_style="medium", color="0000ff")
    >>> double = Side(border_style="dashDot", color="ff0000")
    # рисуем границы
    >>> cell.border = Border(top=double, bottom=double, left=thins, right=thins) 
    >>> wb.save("styled_border.xlsx")
    

    Пример стилизации границ нескольких ячеек:

    from openpyxl import Workbook
    from openpyxl.styles import Border, Side
    
    wb = Workbook()
    ws = wb.active
    
    # определим стили сторон
    thins = Side(border_style="thin", color="0000ff")
    double = Side(border_style="double", color="ff0000")
    
    # начинаем заполнение области ячеек 10x10 данными
    # при этом будем стилизировать границы области 
    for r, row in enumerate(range(5, 15), start=1):
        for c, col in enumerate(range(5, 15), start=1):
            # это значение, которое будем записывать в ячейку
            val_cell = r*c
            # левая верхняя ячейка
            if r == 1 and c == 1:
                ws.cell(row=row, column=col, value=val_cell).border = Border(top=double, left=thins)
            # правая верхняя ячейка
            elif r == 1 and c == 10:
                ws.cell(row=row, column=col, value=val_cell).border = Border(top=double, right=thins)
            # верхние ячейки
            if r == 1 and c != 1 and c != 10:
                ws.cell(row=row, column=col, value=val_cell).border = Border(top=double)
            # левая нижняя ячейка
            elif r == 10 and c == 1:
                ws.cell(row=row, column=col, value=val_cell).border = Border(bottom=double, left=thins)
            # правая нижняя ячейка
            elif r == 10 and c == 10:
                ws.cell(row=row, column=col, value=val_cell).border = Border(bottom=double, right=thins)
            # нижние ячейки
            elif r == 10 and c != 1 and c != 10:
                ws.cell(row=row, column=col, value=val_cell).border = Border(bottom=double)
            # левые ячейки
            elif c == 1 and r != 1 and r != 10:
                ws.cell(row=row, column=col, value=val_cell).border = Border(left=thins)
            # правые ячейки
            elif c == 10 and r != 1 and r != 10:
                ws.cell(row=row, column=col, value=val_cell).border = Border(right=thins)
            else:
                # здесь ячейки просто заполняются данными
                ws.cell(row=row, column=col, value=val_cell)
    
    # сохраняем и смотрим что получилось
    wb.save("styled_border.xlsx")
    

    Заливка ячеек цветом и цвет текста.

    Цвет заливки ячеек выставляется атрибутом ячейки .fill и классом PatternFill().

    Обязательный аргумент fill_type (по умолчанию равен None) класса PatternFill() может принимать значения:

    • если fill_type='solid', то нужно обязательно указывать аргумент цвета заливки fgColor.
    • следующие значения аргумента fill_type применяются самостоятельно (без аргумента fgColor) и представляют собой предустановленные цвета заливки : ‘darkHorizontal’, ‘lightDown’, ‘lightGray’, ‘darkDown’, ‘darkGrid’, ‘darkUp’, ‘darkGray’, ‘darkVertical’, ‘darkTrellis’, ‘mediumGray’, ‘lightVertical’, ‘lightTrellis’, ‘lightGrid’, ‘lightHorizontal’, ‘gray0625’, ‘lightUp’, ‘gray125’.

    Внимание: если аргумент fill_type не указан, то fgColor не будет иметь никакого эффекта!

    Пример заливки одной ячейки:

    >>> from openpyxl import Workbook
    >>> from openpyxl.styles import PatternFill, Font, Alignment
    >>> wb = Workbook()
    >>> ws = wb.active
    # объединим ячейки в диапазоне `B2:E2`
    >>> ws.merge_cells('B2:E2')
    >>> megre_cell = ws['B2']
    # запишем в нее текст
    >>> megre_cell.value = 'Объединенные ячейки `B2 : E2`'
    # установить высоту строки
    >>> ws.row_dimensions[2].height = 30
    # установить ширину столбца
    >>> ws.column_dimensions['B'].width = 40
    # заливка ячейки цветом
    >>> megre_cell.fill = PatternFill('solid', fgColor="DDDDDD")
    # шрифт и цвет текста ячейки 
    >>> megre_cell.font = Font(bold=True, color='FF0000', name='Arial', size=14)
    # ну и для красоты выровним текст
    >>> megre_cell.alignment = Alignment(horizontal='center', vertical='center')
    # сохраняем и смотрим что получилось
    >>> wb.save("cell_color.xlsx")
    

    Именованные стили NamedStyle.

    В отличие от простых стилей ячеек, именованные стили изменяемы и используется для объединения в себе нескольких стилей, таких как шрифты, границы, выравнивание и т. д. Они имеют смысл, когда необходимо применить форматирование к множеству разных ячеек одновременно. Об именованных стилях можно думать как о классах CSS при оформлении HTML-разметки. Именованные стили регистрируются в рабочей книге.

    Примечание. После назначения ячейке именованного стиля, дальнейшие/дополнительные изменения этого стиля не повлияют на стиль ячейки.

    Как только именованный стиль зарегистрирован в рабочей книге, на него можно ссылаться просто по имени.

    Создание именованного стиля.

    >>> from openpyxl.styles import NamedStyle, Font, Border, Side
    # создание переменной именованного стиля
    >>> name_style = NamedStyle(name="highlight")
    # применение стилей к созданной переменной
    >>> name_style.font = Font(bold=True, size=20)
    >>> bd = Side(style='thick', color="000000")
    >>> name_style.border = Border(left=bd, top=bd, right=bd, bottom=bd)
    

    После создания именованного стиля его нужно зарегистрировать в рабочей книге:

    >>> wb.add_named_style(name_style)
    

    Именованные стили также будут автоматически зарегистрированы при первом назначении их ячейке:

    >>> ws['A1'].style = name_style
    

    После регистрации стиля в рабочей книге, применять его можно только по имени:

    >>> ws['D5'].style = 'highlight'
    

    Встроенные стили в Excel.

    Спецификация включает в себя некоторые встроенные стили, которые также могут быть использованы. К сожалению, имена для этих стилей хранятся в их локализованных формах. OpenPyxl узнает только английские имена и только так, как они записаны в официальной документации.

    Использование встроенных в Excel стилей здесь не рассматривается, так как при их применении могу возникать существенные искажения.

    Introduction¶

    Styles are used to change the look of your data while displayed on screen.
    They are also used to determine the formatting for numbers.

    Styles can be applied to the following aspects:

    • font to set font size, color, underlining, etc.
    • fill to set a pattern or color gradient
    • border to set borders on a cell
    • cell alignment
    • protection

    The following are the default values

    >>> from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
    >>> font = Font(name='Calibri',
    ...                 size=11,
    ...                 bold=False,
    ...                 italic=False,
    ...                 vertAlign=None,
    ...                 underline='none',
    ...                 strike=False,
    ...                 color='FF000000')
    >>> fill = PatternFill(fill_type=None,
    ...                 start_color='FFFFFFFF',
    ...                 end_color='FF000000')
    >>> border = Border(left=Side(border_style=None,
    ...                           color='FF000000'),
    ...                 right=Side(border_style=None,
    ...                            color='FF000000'),
    ...                 top=Side(border_style=None,
    ...                          color='FF000000'),
    ...                 bottom=Side(border_style=None,
    ...                             color='FF000000'),
    ...                 diagonal=Side(border_style=None,
    ...                               color='FF000000'),
    ...                 diagonal_direction=0,
    ...                 outline=Side(border_style=None,
    ...                              color='FF000000'),
    ...                 vertical=Side(border_style=None,
    ...                               color='FF000000'),
    ...                 horizontal=Side(border_style=None,
    ...                                color='FF000000')
    ...                )
    >>> alignment=Alignment(horizontal='general',
    ...                     vertical='bottom',
    ...                     text_rotation=0,
    ...                     wrap_text=False,
    ...                     shrink_to_fit=False,
    ...                     indent=0)
    >>> number_format = 'General'
    >>> protection = Protection(locked=True,
    ...                         hidden=False)
    >>>
    

    Cell Styles and Named Styles¶

    There are two types of styles: cell styles and named styles, also known as style templates.

    Cell Styles¶

    Cell styles are shared between objects and once they have been assigned they
    cannot be changed. This stops unwanted side-effects such as changing the
    style for lots of cells when only one changes.

    >>> from openpyxl.styles import colors
    >>> from openpyxl.styles import Font, Color
    >>> from openpyxl import Workbook
    >>> wb = Workbook()
    >>> ws = wb.active
    >>>
    >>> a1 = ws['A1']
    >>> d4 = ws['D4']
    >>> ft = Font(color="FF0000")
    >>> a1.font = ft
    >>> d4.font = ft
    >>>
    >>> a1.font.italic = True # is not allowed # doctest: +SKIP
    >>>
    >>> # If you want to change the color of a Font, you need to reassign it::
    >>>
    >>> a1.font = Font(color="FF0000", italic=True) # the change only affects A1
    

    Copying styles¶

    Styles can also be copied

    >>> from openpyxl.styles import Font
    >>> from copy import copy
    >>>
    >>> ft1 = Font(name='Arial', size=14)
    >>> ft2 = copy(ft1)
    >>> ft2.name = "Tahoma"
    >>> ft1.name
    'Arial'
    >>> ft2.name
    'Tahoma'
    >>> ft2.size # copied from the
    14.0
    

    Colours¶

    Colours for fonts, backgrounds, borders, etc. can be set in three ways: indexed, aRGB or theme. Indexed colours are the legacy implementation and the colours themselves depend upon the index provided with the workbook or with the application default. Theme colours are useful for complementary shades of colours but also depend upon the theme being present in the workbook. It is, therefore, advisable to use aRGB colours.

    aRGB colours¶

    RGB colours are set using hexadecimal values for red, green and blue.

    >>> from openpyxl.styles import Font
    >>> font = Font(color="FF0000")
    

    The alpha value refers in theory to the transparency of the colour but this is not relevant for cell styles. The default of 00 will prepended to any simple RGB value:

    >>> from openpyxl.styles import Font
    >>> font = Font(color="00FF00")
    >>> font.color.rgb
    '0000FF00'
    

    There is also support for legacy indexed colours as well as themes and tints.

    >>> from openpyxl.styles.colors import Color
    >>> c = Color(indexed=32)
    >>> c = Color(theme=6, tint=0.5)
    

    Indexed Colours¶

    Standard Colours

    Index
    0-4 00000000 00FFFFFF 00FF0000 0000FF00 000000FF
    5-9 00FFFF00 00FF00FF 0000FFFF 00000000 00FFFFFF
    10-14 00FF0000 0000FF00 000000FF 00FFFF00 00FF00FF
    15-19 0000FFFF 00800000 00008000 00000080 00808000
    20-24 00800080 00008080 00C0C0C0 00808080 009999FF
    25-29 00993366 00FFFFCC 00CCFFFF 00660066 00FF8080
    30-34 000066CC 00CCCCFF 00000080 00FF00FF 00FFFF00
    35-39 0000FFFF 00800080 00800000 00008080 000000FF
    40-44 0000CCFF 00CCFFFF 00CCFFCC 00FFFF99 0099CCFF
    45-49 00FF99CC 00CC99FF 00FFCC99 003366FF 0033CCCC
    50-54 0099CC00 00FFCC00 00FF9900 00FF6600 00666699
    55-60 00969696 00003366 00339966 00003300 00333300
    60-63 00993300 00993366 00333399 00333333

    The indices 64 and 65 cannot be set and are reserved for the system foreground and background colours respectively.

    Applying Styles¶

    Styles are applied directly to cells

    >>> from openpyxl.workbook import Workbook
    >>> from openpyxl.styles import Font, Fill
    >>> wb = Workbook()
    >>> ws = wb.active
    >>> c = ws['A1']
    >>> c.font = Font(size=12)
    

    Styles can also applied to columns and rows but note that this applies only
    to cells created (in Excel) after the file is closed. If you want to apply
    styles to entire rows and columns then you must apply the style to each cell
    yourself. This is a restriction of the file format:

    >>> col = ws.column_dimensions['A']
    >>> col.font = Font(bold=True)
    >>> row = ws.row_dimensions[1]
    >>> row.font = Font(underline="single")
    

    Styling Merged Cells¶

    The merged cell behaves similarly to other cell objects.
    Its value and format is defined in its top-left cell.
    In order to change the border of the whole merged cell,
    change the border of its top-left cell.
    The formatting is generated for the purpose of writing.

    >>> from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment
    >>> from openpyxl import Workbook
    >>>
    >>> wb = Workbook()
    >>> ws = wb.active
    >>> ws.merge_cells('B2:F4')
    >>>
    >>> top_left_cell = ws['B2']
    >>> top_left_cell.value = "My Cell"
    >>>
    >>> thin = Side(border_style="thin", color="000000")
    >>> double = Side(border_style="double", color="ff0000")
    >>>
    >>> top_left_cell.border = Border(top=double, left=thin, right=thin, bottom=double)
    >>> top_left_cell.fill = PatternFill("solid", fgColor="DDDDDD")
    >>> top_left_cell.fill = fill = GradientFill(stop=("000000", "FFFFFF"))
    >>> top_left_cell.font  = Font(b=True, color="FF0000")
    >>> top_left_cell.alignment = Alignment(horizontal="center", vertical="center")
    >>>
    >>> wb.save("styled.xlsx")
    

    Using number formats¶

    You can specify the number format for cells, or for some instances (ie datetime) it will automatically format.

    >>> import datetime
    >>> from openpyxl import Workbook
    >>> wb = Workbook()
    >>> ws = wb.active
    >>> # set date using a Python datetime
    >>> ws['A1'] = datetime.datetime(2010, 7, 21)
    >>>
    >>> ws['A1'].number_format
    'yyyy-mm-dd h:mm:ss'
    >>>
    >>> ws["A2"] = 0.123456
    >>> ws["A2"].number_format = "0.00" # Display to 2dp
    

    Edit Page Setup¶

    >>> from openpyxl.workbook import Workbook
    >>>
    >>> wb = Workbook()
    >>> ws = wb.active
    >>>
    >>> ws.page_setup.orientation = ws.ORIENTATION_LANDSCAPE
    >>> ws.page_setup.paperSize = ws.PAPERSIZE_TABLOID
    >>> ws.page_setup.fitToHeight = 0
    >>> ws.page_setup.fitToWidth = 1
    

    Named Styles¶

    In contrast to Cell Styles, Named Styles are mutable. They make sense when
    you want to apply formatting to lots of different cells at once. NB. once you
    have assigned a named style to a cell, additional changes to the style will
    not affect the cell.

    Once a named style has been registered with a workbook, it can be referred to simply by name.

    Creating a Named Style¶

    >>> from openpyxl.styles import NamedStyle, Font, Border, Side
    >>> highlight = NamedStyle(name="highlight")
    >>> highlight.font = Font(bold=True, size=20)
    >>> bd = Side(style='thick', color="000000")
    >>> highlight.border = Border(left=bd, top=bd, right=bd, bottom=bd)
    

    Once a named style has been created, it can be registered with the workbook:

    >>> wb.add_named_style(highlight)
    

    But named styles will also be registered automatically the first time they are assigned to a cell:

    >>> ws['A1'].style = highlight
    

    Once registered, assign the style using just the name:

    >>> ws['D5'].style = 'highlight'
    

    Using builtin styles¶

    The specification includes some builtin styles which can also be used.
    Unfortunately, the names for these styles are stored in their localised
    forms. openpyxl will only recognise the English names and only exactly as
    written here. These are as follows:

    • ‘Normal’ # same as no style

    Number formats¶

    • ‘Comma’
    • ‘Comma [0]’
    • ‘Currency’
    • ‘Currency [0]’
    • ‘Percent’

    Informative¶

    • ‘Calculation’
    • ‘Total’
    • ‘Note’
    • ‘Warning Text’
    • ‘Explanatory Text’

    Text styles¶

    • ‘Title’
    • ‘Headline 1’
    • ‘Headline 2’
    • ‘Headline 3’
    • ‘Headline 4’
    • ‘Hyperlink’
    • ‘Followed Hyperlink’
    • ‘Linked Cell’

    Comparisons¶

    • ‘Input’
    • ‘Output’
    • ‘Check Cell’
    • ‘Good’
    • ‘Bad’
    • ‘Neutral’

    Highlights¶

    • ‘Accent1’
    • ‘20 % — Accent1’
    • ‘40 % — Accent1’
    • ‘60 % — Accent1’
    • ‘Accent2’
    • ‘20 % — Accent2’
    • ‘40 % — Accent2’
    • ‘60 % — Accent2’
    • ‘Accent3’
    • ‘20 % — Accent3’
    • ‘40 % — Accent3’
    • ‘60 % — Accent3’
    • ‘Accent4’
    • ‘20 % — Accent4’
    • ‘40 % — Accent4’
    • ‘60 % — Accent4’
    • ‘Accent5’
    • ‘20 % — Accent5’
    • ‘40 % — Accent5’
    • ‘60 % — Accent5’
    • ‘Accent6’
    • ‘20 % — Accent6’
    • ‘40 % — Accent6’
    • ‘60 % — Accent6’
    • ‘Pandas’

    For more information about the builtin styles please refer to the openpyxl.styles.builtins

    The openpyxl Python library provides various different modules to read and modify Excel files. Using this module, we can work on the Excel workbooks very easily and efficiently. In this section, we will discuss how we can add the background color to Excel cells in Python using the openpyxl library.

    Program to add color to Excel cells in Python

    Note: Before starting programming, create an Excel file with some data, or you can choose any of your existing Excel files.

    Example:

    openpyexlinput

     Step1: Import the openpyxl Library and modules to the Python program for adding color to the cell.

    import openpyxl
    from openpyxl.styles import PatternFill

    Note: openpyxl.styles provides various different functions that style your cells in many different ways, like changing the color, font, alignment, border, etc.

    Step2: Connect/Link your Excel workbook file and corresponding workbook’s working Sheet with the Python Program.

    wb = openpyxl.load_workbook("//home//codespeedy//Documents//MyWorkBook.xlsx") #path to the Excel file
    ws = wb['Sheet1'] #Name of the working sheet

    Step3: Call the PaternFill() function with the Pattern type and foreground color parameters of your choice.

    fill_cell = PatternFill(patternType='solid', 
                                fgColor='C64747') #You can give the hex code for different color

    Step4: Lastly, fill the cell with color by using the name of the particular cell of the working sheet, and save the changes to the workbook.

    ws['B2'].fill = fill_cell # B2 is the name of the cell to be fill with color
    wb.save("//home//codespeedy//Documents//MyWorkBook.xlsx")

    Here is the complete Python Program:

    import openpyxl 
    from openpyxl.styles import PatternFill
    
    wb = openpyxl.load_workbook("//home//codespeedy//Documents//MyWorkBook.xlsx")
    ws = wb['Sheet1'] #Name of the working sheet
    
    fill_cell1 = PatternFill(patternType='solid', 
                               fgColor='FC2C03')
    fill_cell2 = PatternFill(patternType='solid', 
                               fgColor='03FCF4') 
    fill_cell3 = PatternFill(patternType='solid', 
                               fgColor='35FC03') 
    fill_cell4 = PatternFill(patternType='solid', 
                               fgColor='FCBA03')  
    
    ws['B2'].fill = fill_cell1
    ws['B3'].fill = fill_cell2
    ws['B4'].fill = fill_cell3
    ws['B5'].fill = fill_cell4
    
    wb.save("//home//sanamsahoo0876//Documents//MyWorkBook.xlsx")

    Now, close the Excel application and reopen it to see the changes.

    Output:

    How to add color to Excel cells using Python

    Hope this article has helped you understand adding color to the Excel cells using Python easily.

    You can also read, Python Program to Merge Excel Cells using openpyxl

    OpenPyXL gives you the ability to style your cells in many different ways. Styling cells will give your spreadsheets pizazz! Your spreadsheets can have some pop and zing to them that will help differentiate them from others. However, don’t go overboard! If every cell had a different font and color, your spreadsheet would look like a mess.

    You should use the skills that you learn in this article sparingly. You’ll still have beautiful spreadsheets that you can share with your colleagues. If you would like to learn more about what styles OpenPyXL supports, you should check out their documentation.

    In this article, you will learn about the following:

    • Working with fonts
    • Setting the alignment
    • Adding a border
    • Changing the cell background-color
    • Inserting images into cells
    • Styling merged cells
    • Using a built-in style
    • Creating a custom named style

    Now that you know what you’re going to learn, it’s time to get started by discovering how to work with fonts using OpenPyXL!

    Working with Fonts

    You use fonts to style your text on a computer. A font controls the size, weight, color, and style of the text you see on-screen or in print. There are thousands of fonts that your computer can use. Microsoft includes many fonts with its Office products.

    When you want to set a font with OpenPyXL, you will need to import the Font class from openpyxl.styles. Here is how you would do the import:

    from openpyxl.styles import Font

    The Font class takes many parameters. Here is the Font class’s full list of parameters according to OpenPyXL’s documentation:

    class openpyxl.styles.fonts.Font(name=None, sz=None, b=None, i=None, charset=None, u=None, 
        strike=None, color=None, scheme=None, family=None, size=None, bold=None, italic=None, 
        strikethrough=None, underline=None, vertAlign=None, outline=None, shadow=None, 
        condense=None, extend=None)

    The following list shows the parameters you are most likely to use and their defaults:

    • name=’Calibri’
    • size=11
    • bold=False
    • italic=False
    • vertAlign=None
    • underline=’none’
    • strike=False
    • color=’FF000000′

    These settings allow you to set most of the things you’ll need to make your text look nice. Note that the color names in OpenPyXL use hexadecimal values to represent RGB (red, green, blue) color values. You can set whether or not the text should be bold, italic, underlined, or struck-through.

    To see how you can use fonts in OpenPyXL, create a new file named font_sizes.py and add the following code to it:

    # font_sizes.py
    
    import openpyxl
    from openpyxl.styles import Font
    
    
    def font_demo(path):
        workbook = openpyxl.Workbook()
        sheet = workbook.active
        cell = sheet["A1"]
        cell.font = Font(size=12)
        cell.value = "Hello"
    
        cell2 = sheet["A2"]
        cell2.font = Font(name="Arial", size=14, color="00FF0000")
        sheet["A2"] = "from"
    
        cell2 = sheet["A3"]
        cell2.font = Font(name="Tahoma", size=16, color="00339966")
        sheet["A3"] = "OpenPyXL"
    
        workbook.save(path)
    
    
    if __name__ == "__main__":
        font_demo("font_demo.xlsx")

    This code uses three different fonts in three different cells. In A1, you use the default, which is Calibri. Then in A2, you set the font size to Arial and increase the size to 14 points. Finally, in A3, you change the font to Tahoma and the font size to 16 points.

    For the second and third fonts, you also change the text color. In A2, you set the color to red, and in A3, you set the color to green.

    When you run this code, your output will look like this:

    Different Fonts in Excel

    Try changing the code to use other fonts or colors. If you want to get adventurous, you should try to make your text bold or italicized.

    Now you’re ready to learn about text alignment.

    Setting the Alignment

    You can set alignment in OpenPyXL by using openpyxl.styles.Alignment. You use this class to rotate the text, set text wrapping, and for indentation.

    Here are the defaults that the Alignment class uses:

    • horizontal=’general’
    • vertical=’bottom’
    • text_rotation=0
    • wrap_text=False
    • shrink_to_fit=False
    • indent=0

    It’s time for you to get some practice in. Open up your Python editor and create a new file named alignment.py. Then add this code to it:

    # alignment.py
    
    from openpyxl import Workbook
    from openpyxl.styles import Alignment
    
    
    def center_text(path, horizontal="center", vertical="center"):
        workbook = Workbook()
        sheet = workbook.active
        sheet["A1"] = "Hello"
        sheet["A1"].alignment = Alignment(horizontal=horizontal,
                                          vertical=vertical)
        sheet["A2"] = "from"
        sheet["A3"] = "OpenPyXL"
        sheet["A3"].alignment = Alignment(text_rotation=90)
        workbook.save(path)
    
    
    if __name__ == "__main__":
        center_text("alignment.xlsx")

    You will center the string both horizontally and vertically in A1 when you run this code. Then you use the defaults for A2. Finally, for A3, you rotate the text 90 degrees.

    Try running this code, and you will see something like the following:

    Aligning Text in Excel

    That looks nice! It would be best if you took the time to try out different text_rotation values. Then try changing the horizontal and vertical parameters with different values. Pretty soon, you will be able to align your text like a pro!

    Now you’re ready to learn about adding borders to your cells!

    Adding a Border

    OpenPyXL gives you the ability to style the borders on your cell. You can specify a different border style for each of the four sides of a cell.

    You can use any of the following border styles:

    • ‘dashDot’
    • ‘dashDotDot’
    • ‘dashed’
    • ‘dotted’
    • ‘double’
    • ‘hair’
    • ‘medium’
    • ‘mediumDashDot’
    • ‘mediumDashDotDot’,
    • ‘mediumDashed’
    • ‘slantDashDot’
    • ‘thick’
    • ‘thin’

    Open your Python editor and create a new file named border.py. Then enter the following code in your file:

    # border.py
    
    from openpyxl import Workbook
    from openpyxl.styles import Border, Side
    
    
    def border(path):
        pink = "00FF00FF"
        green = "00008000"
        thin = Side(border_style="thin", color=pink)
        double = Side(border_style="double", color=green)
    
        workbook = Workbook()
        sheet = workbook.active
    
        sheet["A1"] = "Hello"
        sheet["A1"].border = Border(top=double, left=thin, right=thin, bottom=double)
        sheet["A2"] = "from"
        sheet["A3"] = "OpenPyXL"
        sheet["A3"].border = Border(top=thin, left=double, right=double, bottom=thin)
        workbook.save(path)
    
    
    if __name__ == "__main__":
        border("border.xlsx")

    This code will add a border to cell A1 and A3. The top and bottom of A1 use a “double” border style and are green, while the cell sides are using a “thin” border style and are colored pink.

    Cell A3 uses the same borders but swaps them so that the sides are now green and the top and bottom are pink.

    You get this effect by creating Side objects in the border_style and the color to be used. Then you pass those Side objects to a Border class, which allows you to set each of the four sides of a cell individually. To apply the Border to a cell, you must set the cell’s border attribute.

    When you run this code, you will see the following result:

    Adding a Border to a Cell

    This image is zoomed in a lot so that you can easily see the borders of the cells. It would be best if you tried modifying this code with some of the other border styles mentioned at the beginning of this section so that you can see what else you can do.

    Changing the Cell Background Color

    You can highlight a cell or a range of cells by changing its background color. Highlighting a cell is more eye-catching than changing the text’s font or color in most cases. OpenPyXL gives you a class called PatternFill that you can use to change a cell’s background color.

    The PatternFill class takes in the following arguments (defaults included below):

    • patternType=None
    • fgColor=Color()
    • bgColor=Color()
    • fill_type=None
    • start_color=None
    • end_color=None

    There are several different fill types you can use. Here is a list of currently supported fill types:

    • ‘none’
    • ‘solid’
    • ‘darkDown’
    • ‘darkGray’
    • ‘darkGrid’
    • ‘darkHorizontal’
    • ‘darkTrellis’
    • ‘darkUp’
    • ‘darkVertical’
    • ‘gray0625’
    • ‘gray125’
    • ‘lightDown’
    • ‘lightGray’
    • ‘lightGrid’
    • ‘lightHorizontal’
    • ‘lightTrellis’
    • ‘lightUp’
    • ‘lightVertical’
    • ‘mediumGray’

    Now you have enough information to try setting the background color of a cell using OpenPyXL. Open up a new file in your Python editor and name it background_colors.py. Then add this code to your new file:

    # background_colors.py
    
    from openpyxl import Workbook
    from openpyxl.styles import PatternFill
    
    
    def background_colors(path):
        workbook = Workbook()
        sheet = workbook.active
        yellow = "00FFFF00"
        for rows in sheet.iter_rows(min_row=1, max_row=10, min_col=1, max_col=12):
            for cell in rows:
                if cell.row % 2:
                    cell.fill = PatternFill(start_color=yellow, end_color=yellow,
                                            fill_type = "solid")
        workbook.save(path)
    
    
    if __name__ == "__main__":
        background_colors("bg.xlsx")

    This example will iterate over nine rows and 12 columns. It will set every cell’s background color to yellow if that cell is in an odd-numbered row. The cells with their background color changes will be from column A through column L.

    When you want to set the cell’s background color, you set the cell’s fill attribute to an instance of PatternFill. In this example, you specify a start_color and an end_color. You also set the fill_type to “solid”. OpenPyXL also supports using a GradientFill for the background.

    Try running this code. After it runs, you will have a new Excel document that looks like this:

    Alternating Row Color

    Here are some ideas that you can try out with this code:

    • Change the number of rows or columns that are affected
    • Change the color that you are changing to
    • Update the code to color the even rows with a different color
    • Try out other fill types

    Once you are done experimenting with background colors, you can learn about inserting images in your cells!

    Inserting Images into Cells

    OpenPyXL makes inserting an image into your Excel spreadsheets nice and straightforward. To make this magic happen, you use the Worksheet object’s add_image() method. This method takes in two arguments:

    • img – The path to the image file that you are inserting
    • anchor – Provide a cell as a top-left anchor of the image (optional)

    For this example, you will be using the Mouse vs. Python logo:

    Mouse vs Python Logo

    The GitHub repository for this book has the image for you to use.

    Once you have the image downloaded, create a new Python file and name it insert_image.py. Then add the following:

    # insert_image.py
    
    from openpyxl import Workbook
    from openpyxl.drawing.image import Image
    
    
    def insert_image(path, image_path):
        workbook = Workbook()
        sheet = workbook.active
        img = Image("logo.png")
        sheet.add_image(img, "B1")
        workbook.save(path)
    
    
    if __name__ == "__main__":
        insert_image("logo.xlsx", "logo.png")

    Here you pass in the path to the image that you wish to insert. To insert the image, you call add_image(). In this example, you are hard-coding to use cell B1 as the anchor cell. Then you save your Excel spreadsheet.

    If you open up your spreadsheet, you will see that it looks like this:

    Inserting an Image in an Excel Cell

    You probably won’t need to insert an image into an Excel spreadsheet all that often, but it’s an excellent skill to have.

    Styling Merged Cells

    Merged cells are cells where you have two or more adjacent cells merged into one. If you want to set the value of a merged cell with OpenPyXL, you must use the top left-most cell of the merged cells.

    You also must use this particular cell to set the style for the merged cell as a whole. You can use all the styles and font settings you used on an individual cell with the merged cell. However, you must apply the style to the top-left cell for it to apply to the entire merged cell.

    You will understand how this works if you see some code. Go ahead and create a new file named style_merged_cell.py. Now enter this code in your file:

    # style_merged_cell.py
    
    from openpyxl import Workbook
    from openpyxl.styles import Font, Border, Side, GradientFill, Alignment
    
    
    def merge_style(path):
        workbook = Workbook()
        sheet = workbook.active
        sheet.merge_cells("A2:G4")
        top_left_cell = sheet["A2"]
    
        light_purple = "00CC99FF"
        green = "00008000"
        thin = Side(border_style="thin", color=light_purple)
        double = Side(border_style="double", color=green)
    
        top_left_cell.value = "Hello from PyOpenXL"
        top_left_cell.border = Border(top=double, left=thin, right=thin,
                                      bottom=double)
        top_left_cell.fill = GradientFill(stop=("000000", "FFFFFF"))
        top_left_cell.font = Font(b=True, color="FF0000", size=16)
        top_left_cell.alignment = Alignment(horizontal="center",
                                            vertical="center")
        workbook.save(path)
    
    
    if __name__ == "__main__":
        merge_style("merged_style.xlsx")

    Here you create a merged cell that starts at A2 (the top-left cell) through G4. Then you set the cell’s value, border, fill, font and alignment.

    When you run this code, your new spreadsheet will look like this:

    Styling a Merged Cell

    Doesn’t that look nice? You should take some time and try out some different styles on your merged cell. Maybe come up with a better gradient than the gray one used here, for example.

    Now you’re ready to learn about OpenPyXL’s built-in styles!

    Using a Built-in Style

    OpenPyXL comes with multiple built-in styles that you can use as well. Rather than reproducing the entire list of built-in styles in this book, you should go to the official documentation as it will be the most up-to-date source for the style names.

    However, it is worth noting some of the styles. For example, here are the number format styles you can use:

    • ‘Comma’
    • ‘Comma [0]’
    • ‘Currency’
    • ‘Currency [0]’
    • ‘Percent’

    You can also apply text styles. Here is a listing of those styles:

    • ‘Title’
    • ‘Headline 1’
    • ‘Headline 2’
    • ‘Headline 3’
    • ‘Headline 4’
    • ‘Hyperlink’
    • ‘Followed Hyperlink’
    • ‘Linked Cell’

    OpenPyXL has several other built-in style groups. You should check out the documentation to learn about all the different styles that are supported.

    Now that you know about some of the built-in styles you can use, it’s time to write some code! Create a new file and name it builtin_styls.py. Then enter the following code:

    # builtin_styles.py
    
    from openpyxl import Workbook
    
    
    def builtin_styles(path):
        workbook = Workbook()
        sheet = workbook.active
        sheet["A1"].value = "Hello"
        sheet["A1"].style = "Title"
        
        sheet["A2"].value = "from"
        sheet["A2"].style = "Headline 1"
        
        sheet["A3"].value = "OpenPyXL"
        sheet["A3"].style = "Headline 2"
        
        workbook.save(path)
    
    
    if __name__ == "__main__":
        builtin_styles("builtin_styles.xlsx")

    Here you apply three different styles to three different cells. You use “Title”, “Headline 1” and “Headline 2”, specifically.

    When you run this code, you will end up having a spreadsheet that looks like this:

    Using  Built-in Styles

    As always, you should try out some of the other built-in styles. Trying them out is the only way to determine what they do and if they will work for you.

    But wait! What if you wanted to create your style? That’s what you will cover in the next section!

    Creating a Custom Named Style

    You can create custom styles of your design using OpenPyXL as well. To create your style, you must use the NamedStyle class.

    The NamedStyle class takes the following arguments (defaults are included too):

    • name=”Normal”
    • font=Font()
    • fill=PatternFill()
    • border=Border()
    • alignment=Alignment()
    • number_format=None
    • protection=Protection()
    • builtinId=None
    • hidden=False
    • xfId=None

    You should always provide your own name to your NamedStyle to keep it unique. Go ahead and create a new file and call it named_style.py. Then add this code to it:

    # named_style.py
    
    from openpyxl import Workbook
    from openpyxl.styles import Font, Border, Side, NamedStyle
    
    
    def named_style(path):
        workbook = Workbook()
        sheet = workbook.active
    
        red = "00FF0000"
        font = Font(bold=True, size=22)
        thick = Side(style="thick", color=red)
        border = Border(left=thick, right=thick, top=thick, bottom=thick)
        named_style = NamedStyle(name="highlight", font=font, border=border)
    
        sheet["A1"].value = "Hello"
        sheet["A1"].style = named_style
    
        sheet["A2"].value = "from"
        sheet["A3"].value = "OpenPyXL"
    
        workbook.save(path)
    
    
    if __name__ == "__main__":
        named_style("named_style.xlsx")

    Here you create a Font(), Side(), and Border() instance to pass to your NamedStyle(). Once you have your custom style created, you can apply it to a cell by setting the cell’s style attribute. Applying a custom style is done in the same way as you applied built-in styles!

    You applied the custom style to the cell, A1.

    When you run this code, you will get a spreadsheet that looks like this:

    Using a Custom Named Style

    Now it’s your turn! Edit the code to use a Side style, which will change your border. Or create multiple Side instances so you can make each side of the cell unique. Play around with different fonts or add a custom background color!

    Wrapping Up

    You can do a lot of different things with cells using OpenPyXL. The information in this article gives you the ability to format your data in beautiful ways.

    In this article, you learned about the following topics:

    • Working with fonts
    • Setting the alignment
    • Adding a border
    • Changing the cell background-color
    • Inserting images into cells
    • Styling merged cells
    • Using a built-in style
    • Creating a custom named style

    You can take the information that you learned in this article to make beautiful spreadsheets. You can highlight exciting data by changing the cell’s background color or font. You can also change the cell’s format by using a built-in style. Go ahead and give it a try.

    Experiment with the code in this article and see how powerful and valuable OpenPyXL is when working with cells.

    Related Reading

    • Reading Spreadsheets with OpenPyXL and Python
    • Creating Spreadsheets with OpenPyXL and Python
    • Automating Excel with Python (book)

    Понравилась статья? Поделить с друзьями:
  • Закрасить ячейки по условию vba excel
  • Закрасить ячейки в excel по условию даты
  • Закрасить ячейки в excel макрос
  • Закрасить строку excel макрос
  • Закрасить строки в excel при условии