You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用python-docx读取DOCX文档字号返回None,如何获取默认字号?

解决方案:读取DOCX中继承的字体属性(如字号)

问题原因

你遇到的run.font.size返回None的情况,是因为DOCX的属性存储规则:只有手动修改过的属性才会直接保存在Run对象中,未修改的属性会继承自上级样式(字符样式→段落样式→文档默认样式),而python-docx的run.font仅读取Run自身直接设置的属性,不会自动向上查找继承值。

解决方法

要获取继承的字体属性,需要手动遍历样式层级,从Run本身开始,依次检查其应用的字符样式、段落样式的字符属性,直到文档默认样式(Normal),最终获取有效属性值。

1. 编写继承属性获取函数

下面的函数会递归向上查找样式层级,返回第一个存在的属性值,若所有层级都未设置,则返回Word默认值(可根据实际需求调整):

from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt

def get_inherited_font_size(run):
    # 优先检查Run自身的字号设置
    if run.font.size is not None:
        return run.font.size
    # 遍历样式的继承链
    current_style = run.style
    while current_style is not None:
        if current_style.font.size is not None:
            return current_style.font.size
        current_style = current_style.base_style
    # 所有样式都未设置时,返回Word默认字号
    return Pt(11)

def get_inherited_font_name(run):
    # 同样逻辑适用于字体名
    if run.font.name is not None:
        return run.font.name
    current_style = run.style
    while current_style is not None:
        if current_style.font.name is not None:
            return current_style.font.name
        current_style = current_style.base_style
    # 返回文档默认字体名
    return run.document.styles['Normal'].font.name or 'Calibri'

2. 修改检查函数使用上述方法

更新你的check_para_props函数,替换为继承属性获取逻辑:

def check_para_props(doc, paralist, ffamily, fsize, paligin):
    pargs = doc.paragraphs
    for i in paralist:
        para = pargs[i]
        print(i, para.text)
        for run in para.runs:
            font_name = get_inherited_font_name(run)
            font_size = get_inherited_font_size(run)
            print(font_name, font_size)

worddoc = Document('Foo-bar.docx')
check_para_props(worddoc, (0, ), 'Garamond', 11, WD_ALIGN_PARAGRAPH.JUSTIFY)

补充说明

DOCX的字符属性继承优先级为:

  • Run直接设置的属性 > 应用的字符样式 > 段落样式的字符属性 > 文档默认样式(Normal) > Word程序默认值

如果需要验证其他属性(如粗体、斜体),可以复用同样的逻辑,替换对应的属性(如font.bold、font.italic)即可。

内容的提问来源于stack exchange,提问作者Cs65B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 18:56:01