如何在python-docx生成的双栏布局文档中添加居中标题?
在python-docx中实现双栏文档顶部居中标题
你遇到的问题根源在于:默认情况下标题和双栏内容处于同一个**节(Section)**中,所以标题会被纳入双栏布局的范围,最终显示在左栏里。要解决这个问题,核心思路是把标题单独放在一个通栏的节中,之后再创建双栏布局的节,让标题不受双栏规则影响,自然居中在文档顶部。
问题复现代码
你之前的代码会导致标题被包含在双栏节内:
from docx import Document from docx.shared import Inches from docx.shared import Pt from docx.enum.section import WD_SECTION from docx.oxml.ns import qn doc = Document() # Title title = doc.add_heading('THIS IS THE TITLE') section = doc.sections[0] sectPr = section._sectPr cols = sectPr.xpath('./w:cols')[0] cols.set(qn('w:num'),'2') # Left column par1 = doc.add_paragraph('FIRST PAR IN THE LEFT COLUMN(testingtestingtestingtestingtestingtestingtestingtestingtestingtesting)') # Right column current_section = doc.sections[-1] current_section.start_type new_section = doc.add_section(WD_SECTION.NEW_COLUMN) new_section.start_type par2 = doc.add_paragraph('FIRST PAR IN THE RIGHT COLUMN(testingtestingtestingtestingtestingtestingtestingtestingtestingtesting)') # Save Doc doc.save('demo.docx')
解决方案代码
通过将标题、双栏内容分别放在独立的节中,就能实现标题居中在文档顶部、下方显示双栏内容的效果:
from docx import Document from docx.shared import Inches from docx.shared import Pt from docx.enum.section import WD_SECTION from docx.oxml.ns import qn doc = Document() # 第一个节:通栏布局,放置标题 new_section = doc.add_section(WD_SECTION.CONTINUOUS) title_heading = doc.add_heading('This is the title!!!!!!!!!!!!!') title_heading.alignment = 1 # 1对应居中对齐 # 第二个节:设置为双栏布局 new_section = doc.add_section(WD_SECTION.CONTINUOUS) section = doc.sections[-1] sectPr = section._sectPr cols = sectPr.xpath('./w:cols')[0] cols.set(qn('w:num'), '2') # 左栏内容 left_paragraph = doc.add_paragraph('This is the 1st para') left_paragraph.alignment = 1 # 第三个节:切换到右栏 new_section = doc.add_section(WD_SECTION.NEW_COLUMN) right_paragraph = doc.add_paragraph('This is the 2nd para') right_paragraph.alignment = 1 # 保存文档 doc.save('demo.docx')
关键说明
- 节是Word文档中布局设置的基本单元,不同布局(通栏/双栏)需要放在独立的节中;
- 使用
WD_SECTION.CONTINUOUS可以让新节紧跟在上一节之后,避免不必要的分页; heading.alignment = 1是直接用数值设置居中对齐,和调用WD_ALIGN_PARAGRAPH.CENTER效果一致,写法更简洁。
内容的提问来源于stack exchange,提问作者Salman.S




