Hello to all! In continuation of articles on working with Openpyxl today, let’s try to figure out: how to change the font and color in a cell?
We’ll begin to understand – and for practical purposes, create an Excel file in which we will create a cell with text that will be:
- Have some size
- Colour
- Underline
- Incline
- The text will be bold
We begin to code:
-
import openpyxl #Connect the library
-
from openpyxl import Workbook
-
from openpyxl.styles import PatternFill#Connect cell styles
-
from openpyxl.workbook import Workbook
-
from openpyxl.styles import Font, Fill#Connect styles for text
-
from openpyxl.styles import colors#Connect colors for text and cells
-
wb = openpyxl.Workbook() #Create book
-
work_sheet = wb.create_sheet(title=’Test sheet’) #Created a sheet with a name and made it active
-
-
work_sheet['A1'] = 'Test text'
-
work_sheet_a1 = work_sheet['A5']#Created a variable that contains cell A1 with the existing text
-
work_sheet_a1.font = Font(size=23, underline='single', color='FFBB00', bold=True, italic=True) #We apply the following parameters to the text: size - 23, underline, color = FFBB00 (text color is specified in RGB), bold, oblique. If we do not need a bold font, we use the construction: bold = False. We act similarly if we do not need an oblique font: italic = False.
-
-
Important: if necessary, the possibility of using standard colors is included in the styles, but the code in this case will look different:
-
work_sheet_a1.font = Font(size=23, underline='single', color = colors.RED, bold=True, italic=True) #what color = colors.RED — color prescribed in styles
-
work_sheet_a1.fill = PatternFill(fill_type='solid', start_color='ff8327', end_color='ff8327')#This code allows you to do design color cells
Important: to work with the design of columns or rows, another algorithm is used, which we will talk about later.
By the way, below is the code for a simple program that creates a page and writes text in cells from a unit to the specified one.
-
import openpyxl #Подключаем библиотеку
-
from openpyxl.styles import Font, Fill
-
wb = openpyxl.Workbook() #Создали книгу
-
work_sheet = wb.create_sheet(title='Test sheet') #Создали лист с названием и сделали его активным
-
a = int(input('Введите а: '))
-
cell_a = 'A'
-
i = 1
-
while i <= a:
-
i = str(i)
-
cell = cell_a + i
-
work_sheet[cell] = 'Test text'
-
work_sheet_a1 = work_sheet[cell]
-
work_sheet_a1.font = Font(size=i)
-
i = int(i)
-
i = i + 1
-
wb.save('ok.xlsx')
Thanks for attention! On a topic that sounds like “Openpyxl – how to change the font and color in a cell” – there is nothing more to say ? Do not forget to repost ?