How do I change the font size of a cell? I am using OpenPyXL.
It will not let me send this question without typing the above with perfect grammar and spelling, so the last few words people should know what I mean.
How do I change the font size of a cell? I am using OpenPyXL.
It will not let me send this question without typing the above with perfect grammar and spelling, so the last few words people should know what I mean.
This works for me:
from openpyxl.styles import Font
fontStyle = Font(size = "10")
ws.cell(row = 1, column = 1, value = 'Test Text').font = fontStyle
I'm using openpyxl version: 2.3.2
In openpyxl handling styles changes a bit between the version.
The current version (as of writing 3.0.6) handles font object as immutable and has deprecated the font.copy(...)
function.
Therefore the only way I figured out only change the font size (and keep the rest as it is) is:
ws.cell(1, 1).font += Font(size=new_font_size-ws.cell(1, 1).font)
Font is an openpyxl.descriptors.serialisable.Serialisable
object for which that add operator is implemented and recommended by the
DeprecationWarning: Call to deprecated function copy (Use copy(obj) or cell.obj = cell.obj + other).
Only Problem is that, using the __add__
operator will add the given font size with the original one. Therefore the original one has to be subtracted.
from openpyxl import load_workbook, worksheet, cell
from openpyxl.styles import Font
def change_fontsize(cell: cell, fontsize: float):
orig_size = cell.font.size
cell.font += Font(size=fontsize - orig_size)
input_filename = "to_modify.xlsx"
wb = load_workbook(input_filename)
# Get first sheet
sh: worksheet = wb[wb.sheetnames[0]]
change_fontsize(sh.cell(1,1), 5)
wb.save('modified.xlsx')
As this functionality is not really documented in openpyxl I assume that one can't assume that this will be stable.
Currently it works only because of the implementation of the default values of Fonts __init__
function, which all evaluate False
.
This code opens a *.xlsx file and edits the style of cell 'A1' so it has font size 20. I newer versions of openpyxl you get an error message if you try to overwrite the font directly.
import openpyxl
from openpyxl.styles import Font
path = 'filename.xlsx'
book = openpyxl.load_workbook(path)
ws, *ows = book
ws['A1'].font = Font(size=20)
book.save(path)
The *ows will place any other sheets then the first inside a list, if there is only one worksheet the list will be empty. (ows=[])
Openpyxl styling can achieve this for you!
cell.style.font.size = "font size goes here as integer"