Python 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

Looks like the sheet is using the built-on colour index. The mapping for these is in the source of openpyxl.styles.color

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

11L corresponds to 0000FF00 (hexadecimal) for which the rgb tuple would be green (0,255,0).

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 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)

    Как узнать цвет ячейки в Excel-файле с помощью Python

    Привет всем! Обычно вопросы (пусть и не многочисленные, но от этого не менее интересные) мне приходят на почту или в Telegram. Сегодня вопрос был задан в Facebook: Как узнать цвет ячейки в Excel-файле с помощью Python? Ответ, как всегда после того, как разберешься — оказывается весьма простым:

    1. import openpyxl #Подключаем библиотеку <a href="https://openpyxl.readthedocs.io" rel="noopener noreferrer" target="_blank">Openpyxl</a>
    2. path = 'path to file'
    3. workbook = openpyxl.load_workbook(path) #Собственно - читаем сам файл
    4. sheets_list = workbook.sheetnames #Получаем список всех листов в книге
    5. sheet_active = workbook[sheets_list[0]] #Делаем активным самый первый лист в книге
    6.  
    7. cell_fill = sheet_active['A1'].fill.start_color.index #Получаем цвет ячейки
    8. cell_fill = '#' + cell_fill
    9. print(cell_fill) #Выводим на экран :)

    Собственно, это все 🙂 Спасибо за внимание! Как всегда — для вопросов открыта почта и есть Telegram 🙂

    Больше …

    Больше ...

    Привет всем! Только что столкнулся с задачей работы со временем…

    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

    What will we cover in this tutorial?

    We will learn how you can dynamically format the cells in Excel to have a specific color based on the value of a function – all done from Python.

    As an example we will color the cells of two columns depending on which is larger.

    If the value in MA50 is larger than value in MA200 it will color green and red otherwise.

    In this concrete example we will collect historical stock prices and calculate the Moving Averages of 50 and 200 days on the closing price. In a crossover way to utilize moving averages, you would send a buy-signal when the 50-day moving average crosses above the 200-day moving average and a sell-signal if the other way around.

    Step 1: Collect the data from Yahoo! Finance using Pandas-datareader

    A great library to use to collect financial data is the Pandas-datareader.

    We will collect data from Yahoo! Finance. As an example we will use General Motors historical stock data.

    This can be done as follows.

    import pandas_datareader as pdr
    import datetime as dt
    
    start = dt.datetime(2019, 1, 1)
    ticker = pdr.get_data_yahoo("GM", start)
    

    This will result in a Pandas DataFrame with data similar to this.

                     High        Low       Open      Close      Volume  Adj Close
    Date                                                                         
    2019-01-02  33.810001  32.410000  32.849998  33.639999   7662300.0  31.893360
    2019-01-03  33.680000  32.200001  33.340000  32.250000  11618300.0  30.575533
    2019-01-04  33.570000  32.430000  32.799999  33.330002  10784000.0  31.599455
    2019-01-07  34.970001  33.480000  33.709999  34.360001  10722300.0  32.575977
    2019-01-08  35.680000  34.490002  35.000000  34.810001  10532900.0  33.002617
    

    Step 2: Calculate the Moving Averages

    The moving average can be calculated by applying the rolling() and mean() methods on the DataFrame.

    The rolling() creates a window size which is the number of observations used for calculating the statistic.

    To calculate the Moving Average of window size 50 will use the last 50 data points to calculate the mean. To be consistent with Yahoo! Finance way of calculate the value, they use the Close price.

    import pandas_datareader as pdr
    import datetime as dt
    import xlsxwriter
    import pandas as pd
    
    start = dt.datetime(2019, 1, 1)
    ticker = pdr.get_data_yahoo("GM", start)
    ticker['MA50'] = ticker['Close'].rolling(50).mean()
    ticker['MA200'] = ticker['Close'].rolling(200).mean()
    

    Which will give a tail similar to this output.

                     High        Low       Open  ...  Adj Close     MA50     MA200
    Date                                         ...                              
    2020-12-14  42.540001  41.419998  42.490002  ...  41.619999  38.5632  29.03155
    2020-12-15  42.160000  41.310001  41.990002  ...  41.660000  38.7772  29.08725
    2020-12-16  41.869999  40.810001  41.790001  ...  41.419998  38.9976  29.13670
    2020-12-17  42.029999  41.430000  41.709999  ...  42.029999  39.2058  29.19635
    2020-12-18  42.042801  41.139999  42.020000  ...  41.389999  39.3894  29.25985
    

    Where the Moving Averages are added to the DataFrame.

    Step 3: Exporting to Excel using XlsxWriter

    We will use the powerful XlsxWriter to create our Excel sheet.

    You can write the DataFrame directly by using to_excel(…), but we want to do more than that. Hence, we use the XlsxWriter directly.

    import pandas_datareader as pdr
    import datetime as dt
    import pandas as pd
    
    start = dt.datetime(2019, 1, 1)
    ticker = pdr.get_data_yahoo("GM", start)
    ticker['MA50'] = ticker['Close'].rolling(50).mean()
    ticker['MA200'] = ticker['Close'].rolling(200).mean()
    # We only want the index as a date and not datetime object
    ticker.index = ticker.index.date
    # We skip the first 200 entries, as it they do not have the MA200
    ticker = ticker.iloc[200:]
    # We reverse the DataFrame to have newest first
    ticker = ticker.iloc[::-1]
    # Create a Pandas Excel writer using XlsxWriter as the engine.
    writer = pd.ExcelWriter('moving_average.xlsx', engine='xlsxwriter')
    # Convert the dataframe to an XlsxWriter Excel object.
    ticker.to_excel(writer, sheet_name='Moving Averages')
    # Remember to close the writer to write the Excel sheet
    writer.close()
    

    This will create an Excel sheet similar to this one.

    Step 4: Adding formatting to the cells

    This is a bit more complex as we need to do the magic here.

    We first need to create a reference to the sheet (worksheet) we work on to access the functionality.

    The first thing we do is to resize column A, such that it opens in the correct size to see the date. This is done by using set_column(…).

    Then we create a format, which can be applied on Excel cells. This is how we color them. Hence, we create one for green cells and later one for red cells.

    We insert them by using conditional_format(…), which a range of cells. This can be applied in different ways, we use the A1 notation.

    The options parameter in conditional_format(…) must be a dictionary containing the parameters that describe the type and style of the conditional format. To see details of the format please refer to the manual.

    import pandas_datareader as pdr
    import datetime as dt
    import pandas as pd
    
    start = dt.datetime(2019, 1, 1)
    ticker = pdr.get_data_yahoo("GM", start)
    ticker['MA50'] = ticker['Close'].rolling(50).mean()
    ticker['MA200'] = ticker['Close'].rolling(200).mean()
    # We only want the index as a date and not datetime object
    ticker.index = ticker.index.date
    # We skip the first 200 entries, as it they do not have the MA200
    ticker = ticker.iloc[200:]
    # We reverse the DataFrame to have newest first
    ticker = ticker.iloc[::-1]
    # Create a Pandas Excel writer using XlsxWriter as the engine.
    writer = pd.ExcelWriter('moving_average.xlsx', engine='xlsxwriter')
    # Convert the dataframe to an XlsxWriter Excel object.
    ticker.to_excel(writer, sheet_name='Moving Averages')
    # Get the xlsxwriter objects from the dataframe writer object.
    workbook = writer.book
    worksheet = writer.sheets['Moving Averages']
    # Resize the column A
    worksheet.set_column("A:A", 12)
    # Calculate the last row number (we insert first DataFrame row in row 2)
    last_row = len(ticker) + 1
    # Create a format for a green cell
    cell_format_green = workbook.add_format()
    cell_format_green.set_bg_color('green')
    # Create a conditional formatted of type formula
    worksheet.conditional_format('H2:I{}'.format(last_row), {'type':     'formula',
                                                             'criteria': '=$H2>=$I2',
                                                             'format':   cell_format_green})
    # Create a format for a red cell
    cell_format_red = workbook.add_format()
    cell_format_red.set_bg_color('red')
    # Create a conditional formatted of type formula
    worksheet.conditional_format('H2:I{}'.format(last_row), {'type':     'formula',
                                                             'criteria': '=$H2<$I2',
                                                             'format':   cell_format_red})
    # Remember to close the writer
    writer.close()
    

    This will result in the expected Excel sheet.

    Step 5: Validating it works as expected

    Now for the final test.

    The colors should be updated dynamically. Let’s try to change the value and see what happens.

    It does. If we change the value of H2 to 10, it turns the cells to red.

    Python Circle

    Do you know what the 5 key success factors every programmer must have?

    How is it possible that some people become programmer so fast?

    While others struggle for years and still fail.

    Not only do they learn python 10 times faster they solve complex problems with ease.

    What separates them from the rest?

    I identified these 5 success factors that every programmer must have to succeed:

    1. Collaboration: sharing your work with others and receiving help with any questions or challenges you may have.
    2. Networking: the ability to connect with the right people and leverage their knowledge, experience, and resources.
    3. Support: receive feedback on your work and ask questions without feeling intimidated or judged.
    4. Accountability: stay motivated and accountable to your learning goals by surrounding yourself with others who are also committed to learning Python.
    5. Feedback from the instructor: receiving feedback and support from an instructor with years of experience in the field.

    I know how important these success factors are for growth and progress in mastering Python.

    That is why I want to make them available to anyone struggling to learn or who just wants to improve faster.

    With the Python Circle community, you can take advantage of 5 key success factors every programmer must have.

    Python Circle

    Python Circle

    Be part of something bigger and join the Python Circle community.

    Last Updated on July 14, 2022 by

    This tutorial will show you how to use the Python openpyxl library to customize Excel formatting such as cell color, alignment, borderlines, etc. We’ll continue with the previous example to make our monthly budget spreadsheet look prettier.

    Library

    The only library required is openpyxl, type the following in the command prompt window to install the library:

    pip install openpyxl

    In openpyxl, each Cell object has a bunch of attributes we can use for formatting:

    Attribute Usage
    Cell.font font style, size, color, etc
    Cell.number_format number formats
    Cell.fill cell color and pattern
    Cell.border cell border
    Cell.alignment text alignment

    Collectively, these attributes are called styles but I still prefer calling them just formats. One thing to note is that we can apply styles to only one cell at a time. So we’ll need to do a loop in order to format a range of cells.

    Color – Pattern (solid) Fill

    There are two types of cell color formatting: Pattern Fill and Gradient Fill.

    We use Pattern Fill to make a solid color or a pattern for the cell. A Pattern Fill refers to the following formatting in Excel:

    Excel Format Cells window
    Excel Format Cells window

    The below code changes cells B11:C11 to a light gray background and changes cells B19:C19 to a dotted background known as 6.25% Gray (found in the Pattern Style dropbox). To make the formatting easier to see, we’ll hide all gridlines in Excel by setting ws.sheet_view.showGridLines to False.

    from openpyxl.styles import PatternFill, GradientFill
    ws.sheet_view.showGridLines = False
    
    for c in ws['B11:C11'][0]:
        c.fill = PatternFill('solid', fgColor = 'F2F2F2')
    
    for c in ws['B19:C19'][0]:
        c.fill = PatternFill('gray0625')
    openpyxl fills cell background color
    openpyxl fills cell background color

    Color – Gradient Fill

    A Gradient Fill usually takes two colors and interpolates colors between them and fills the cell background. The following code takes a cyan color (’85E4F7′) and a light blue color (‘4617F1’) for the gradient fill. You can change the two RGB hex code inside the stop argument to any color to create your own gradient fill.

    ws['E7'].fill = GradientFill('linear', stop = ('85E4F7','4617F1'))
    ws['E9'].fill = GradientFill('linear', stop = ('85E4F7','4617F1'))
    ws['E11'].fill = GradientFill('linear', stop = ('85E4F7','4617F1'))
    ws['E13'].fill = GradientFill('linear', stop = ('85E4F7','4617F1'))
    openpyxl fills cell background color
    openpyxl fills cell background color

    Borderlines

    Borderlines refer to the four sides of a cell. With openpyxl, we can control the style (solid vs dash, etc), thickness, color, and position of the borderlines. We need two objects to model a cell’s borderline: Border and Side.

    A Border can contain one or multiple Sides. Then we assign the cell.border attribute to a Border object to create the borderlines.

    from openpyxl.styles import Border, Side
    
    double = Side(border_style="double", color="4617F1")
    thin = Side(border_style="thin", color="4617F1")
    regular = Side(border_style="medium", color="000000")
    
    ## For the title cells B2 to F2
    for c in ws['B2:F2'][0]:
        c.border = Border(bottom=double, top=thin)
    
    
    
    no_left_side = Border(top = regular,bottom=regular,right=regular)
    no_right_side = Border(top = regular,bottom=regular, left=regular)
    box = Border(top = regular,bottom=regular, left=regular,right=regular)
    
    ## For the "table-like" cells
    for c in ws['B8:B11']+ws['B15:B19']:
        c[0].border = no_left_side
        
    for c in ws['C8:C11']+ws['C15:C19']:
        c[0].border = no_right_side
    openpyxl draws cell borderlines
    openpyxl draws cell borderlines

    Text Alignment

    We use the Alignment object to model text/number alignment within a cell, then assign the cell.alignment attribute to the object.

    from openpyxl.styles import Alignment
    
    center_align = Alignment(horizontal='center', vertical='center')
    
    for c in ws['C8:C11']+ws['C15:C19']:
        c[0].border = no_right_side
        c[0].alignment = center_align
    
    for c in ws['F7:F14']:
        c[0].alignment = center_align
    openpyxl text alignment
    openpyxl text alignment

    Additional Resources

    Python & Excel – Number Format

    Python openpyxl – How to Insert Rows, Columns in Excel

    Adjust Excel Fonts using Python openpyxl

    Write Data to Excel using Python

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