You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何通过python-docx样式分别设置正文12号、表格9号字体?

用python-docx通过样式实现正文与表格文字字号分离

问题根源

python-docx中表格的每个单元格默认包含一个使用Normal(正文)样式的段落,所以直接修改Normal样式的字号时,表格内的文字会自动继承这个设置。要实现正文12磅、表格9磅的分离效果,关键是给表格单元格的段落指定独立的样式,切断和Normal的继承关联。

方法1:修改内置表格样式

直接调整python-docx内置的表格样式字体大小,创建表格时应用该样式即可:

from docx import Document
from docx.shared import Pt

doc = Document()

# 设置正文Normal样式为12磅
normal_style = doc.styles['Normal']
normal_style.font.size = Pt(12)

# 添加正文内容
doc.add_paragraph('这是12磅的正文文本')

# 修改内置表格样式(比如Table Grid)的字体为9磅
table_style = doc.styles['Table Grid']
table_style.font.size = Pt(9)

# 创建表格并应用该样式
table = doc.add_table(rows=2, cols=2, style='Table Grid')
# 填充表格内容
for row in table.rows:
    for cell in row.cells:
        cell.text = '这是9磅的表格文本'

doc.save('styled_doc.docx')

提示:如果内置表格样式包含标题行、特殊列的差异化设置,需要确认修改的是该样式的基础字体属性,确保所有单元格统一生效。

方法2:创建自定义表格单元格样式

如果不想改动内置样式,可新建一个专属的段落样式,专门用于表格单元格:

from docx import Document
from docx.shared import Pt
from docx.enum.style import WD_STYLE_TYPE

doc = Document()

# 设置正文Normal样式为12磅
normal_style = doc.styles['Normal']
normal_style.font.size = Pt(12)

# 添加正文内容
doc.add_paragraph('这是12磅的正文文本')

# 创建自定义表格单元格样式
table_cell_style = doc.styles.add_style('TableCellStyle', WD_STYLE_TYPE.PARAGRAPH)
table_cell_style.font.size = Pt(9)
# 可按需调整对齐、缩进等属性,保持表格默认排版
table_cell_style.paragraph_format.alignment = None

# 创建表格并给每个单元格的段落应用自定义样式
table = doc.add_table(rows=2, cols=2)
for row in table.rows:
    for cell in row.cells:
        cell.text = '这是9磅的表格文本'
        cell.paragraphs[0].style = table_cell_style

doc.save('custom_style_doc.docx')

这种方式灵活性更高,不会影响其他使用内置样式的表格。

方法3:指定表格默认段落样式

还可以直接给表格的所有单元格段落指定独立样式,跳过继承逻辑:

from docx import Document
from docx.shared import Pt
from docx.enum.style import WD_STYLE_TYPE

doc = Document()

# 设置正文Normal样式为12磅
normal_style = doc.styles['Normal']
normal_style.font.size = Pt(12)

# 添加正文内容
doc.add_paragraph('这是12磅的正文文本')

# 创建表格专用的段落样式
table_paragraph_style = doc.styles.add_style('TableParagraph', WD_STYLE_TYPE.PARAGRAPH)
table_paragraph_style.font.size = Pt(9)

# 创建表格后批量应用样式
table = doc.add_table(rows=2, cols=2)
for row in table.rows:
    for cell in row.cells:
        cell.paragraphs[0].style = table_paragraph_style
        cell.text = '这是9磅的表格文本'

doc.save('table_default_style.docx')

注意事项

  • 不要试图通过修改Normal样式来单独控制正文,表格单元格的段落默认必然继承该样式。
  • 内置表格样式适合批量统一设置,自定义样式适合个性化需求场景。
  • 如果使用模板创建文档,需确认模板中的表格样式未被锁定或存在异常继承关系。

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

火山引擎 最新活动