简体   繁体   中英

How to change font size in Python OpenPyXL

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

openpyxl > 3.0 (2021)

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)

Explained

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.

Full Example with Function

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

Stability Note

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 样式可以为您实现这一点!

cell.style.font.size = "font size goes here as integer"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM