Write text to excel sheet using python but with different formats in a single cell

47 Views Asked by At

How can we concatenate two strings which are with different formats (like one in black & other in red color) to be pasted in a single cell in Excel's sheet through python code ?

from openpyxl import Workbook
from openpyxl.styles import Font

# Create a new Excel workbook
workbook = Workbook()
worksheet = workbook.active

# Write "Hello" in black
cell_hello = worksheet.cell(row=1, column=1)
cell_hello.value = "Hello"
cell_hello.font = Font(color="000000")  # Black font color

# Write "world" in red
cell_world = worksheet.cell(row=1, column=2)
cell_world.value = "world"
cell_world.font = Font(color="FF0000")  # Red font color

# Save the workbook
workbook.save(filename="../hello_world.xlsx")

But, how to write the data to be in a single cell ?

1

There are 1 best solutions below

0
Timeless On

You can work with Rich Texts :

from openpyxl import Workbook
from openpyxl.cell.text import InlineFont
from openpyxl.cell.rich_text import TextBlock, CellRichText

wb = Workbook()
ws = wb.active

def fn(t, rt, c, sep=" ", **inf_kw):
    return CellRichText(
        [t + sep, TextBlock(InlineFont(color=c, **inf_kw), rt)]
    )

ws["A1"] = fn("Stack", "Overflow", "FFA500", b=True)

wb.save("output.xlsx")

Output :

enter image description here