利用python docx调整word页面及表格格式(包含页眉页脚设置)

1. 页面布局

import docx
from docx import Document 
document = docx.Document()
    
    
##页面布局为横向
sections=document.sections
section=sections[0]
new_pagewidth,new_pageheight=section.page_height,section.page_width
#设置三个参数
section.orientation = WD_ORIENT.LANDSCAPE
section.page_height=new_pageheight
section.page_width=new_pagewidth

如果不设置pageheight 和pagewidth 那么转向就没有用啦
    

2. 页边距调整

    #changing the page margins修改页边距
    sections = document.sections 
    for section in sections: 
        section.top_margin = Cm(3) 
        section.bottom_margin = Cm(2) 
        section.left_margin = Cm(2.54) 
        section.right_margin = Cm(2.54) ##Cm 需要import 一下

3. 插入页眉(文字加表格)

 ##插入页眉
##页眉离页面顶端距离
##页脚离页面低端距离
    document.sections[0].header_distance = Cm(1.5) 
    document.sections[0].footer_distance = Cm(1.75)
    header = document.sections[0].header # 获取第一个节的页眉(所有的页眉都一致)
    
    
    paragraph = header.paragraphs[0] # 获取页眉的文字part
    text=paragraph.add_run('my header')
    text.font.size = Pt(10)                # 页眉字体大小
    text.bold = True                    # 页眉字体是否加粗
    text.font.name = 'Arial'           # 控制是英文时的字体
    text.element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 控制是中文时的字体
    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER ##设置页眉居中



    ##在页眉中插入表格
    table_h = header.add_table(rows=1, cols=3,wid
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值