python-docx页眉横线

本文介绍了如何利用python-docx库在Word文档中制作页眉横线,包括两种方法:一是利用下划线和制表位设置,支持18种格式;二是直接修改源代码添加边框,但需手动更新模块。内容涵盖了段落格式设置、制表位定位和横线样式调整等细节。
摘要由CSDN通过智能技术生成

页眉横线实际上是一种边框形式

方法一下划线仅支持18种格式,详见Word 中的 WdUnderline (枚举) | Microsoft Docs

方法二支持页眉横线所有样式,但需要修改源代码,详见OOXML w:ST_Border - 完整的文档和示例 (datypic.com)

方法一:使用docx下划线及tab-stop制作页眉横线

import docx
import os
import subprocess
from docx import Document

# from win32com.client import Dispatch 
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.text import WD_UNDERLINE
from docx.enum.text import WD_TAB_ALIGNMENT
from docx.enum.table import WD_ROW_HEIGHT_RULE
from docx.enum.text import WD_LINE_SPACING

class xxxx():

    def loadfile(self):
        pass
    
    def header(self,file):

        document = Document(file) # 新建文档
        #设置页眉
        header = document.sections[0].header # 获取第一个节的页眉
        # 通过分区添加页眉横线
        header.add_paragraph(
            "\t\t"
        ).paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        header_para = header.paragraphs[-1]
        # style1:与页边距齐平
        header_para.paragraph_format.left_indent = 0
        header_para.paragraph_format.right_indent = 0
        # #style2:横穿整个页面故段落边距紧贴页边
        # header_para.paragraph_format.left_indent = - document.sections[0].left_margin
        # header_para.paragraph_format.right_indent = - document.sections[0].right_margin
        # 设置制表位分区
        tab_stops = header_para.paragraph_format.tab_stops
        tab_stops.add_tab_stop(docx.shared.Inches(3.5), WD_TAB_ALIGNMENT.CENTER)
        tab_stops.add_tab_stop(docx.shared.Inches(6.5), WD_TAB_ALIGNMENT.RIGHT)
        # 设置横线样式
        header_para.runs[-1].underline = WD_UNDERLINE.THICK #厚 DOUBLE双下划线
        #行高为确定值
        header_para.height_rule = WD_ROW_HEIGHT_RULE.EXACTLY
        header_para.height = docx.shared.Pt(1)
        #line_space为确定值
        header_para.paragraph_format.line_spacing_rule = WD_LINE_SPACING.EXACTLY 
        header_para.line_spacing = docx.shared.Pt(1)

上述代码引用包说明:

import subprocess

from win32com.client import Dispatch

目的均为使doc转为docx文件,

前一种是mac下载LibreOffice后使用;后一种仅支持win(mac不能用,原理貌似是pypiwin32是将文件以win32位二进制流编写转码,仅支持win。详见stackover)


方法二:修改源代码,添加border

见该pull request修改代码:(红的删除,绿的添加)但由于这种方式并未merge到module,需要手动更新。下一步计划:学习XML,读懂python-docx文档达到能自己改源码的水平



Enable python-docx to add border by xxxspy · Pull Request #326 · python-openxml/python-docx · GitHub

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值