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

如何去除python-docx中添加标题时自动生成的水平线?

去除python-docx添加标题后的水平线问题

用add_heading(self.doc_title, 0)添加的标题,默认套用了Word内置的「Title」样式,这个样式自带底部边框,所以会显示出一条水平线。可以通过两种方式去除:

方法一:修改单个标题的边框

添加标题后,直接获取对应的段落对象,将底部边框宽度设为0:

main_title = self.document.add_heading(self.doc_title, 0)
# 获取标题段落
title_paragraph = main_title
# 把底部边框宽度设为0,移除水平线
title_paragraph.paragraph_format.bottom_border.width = 0

或者通过边框样式枚举来设置:

from docx.enum.text import WD_BORDER

main_title = self.document.add_heading(self.doc_title, 0)
title_paragraph = main_title
# 将底部边框设置为无
title_paragraph.paragraph_format.bottom_border.style = WD_BORDER.NONE

方法二:修改全局「Title」样式

如果需要批量添加无水平线的标题,可以先修改内置的「Title」样式,后续所有level=0的标题都会自动应用修改后的样式:

# 获取文档内置的Title样式
title_style = self.document.styles['Title']
# 移除样式的底部边框
title_style.paragraph_format.bottom_border.width = 0

# 之后添加的level=0标题就不会有水平线了
main_title = self.document.add_heading(self.doc_title, 0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:02:35