Python实现自动化Word排版

 更新时间:2025年04月21日 10:06:45   作者:丹尼尔Aldridge  
Word是一款广泛使用的文档编辑工具,但在排版过程中可能会遇到繁琐的重复操作,下面我们就来学习一下如何使用Python实现自动化的Word排版,让文档编辑变得更加高效便捷吧

Word是一款广泛使用的文档编辑工具,但在排版过程中可能会遇到繁琐的重复操作。幸运的是,借助Python编程语言的强大功能,我们可以实现自动化的Word排版,提升文档编辑的效率和质量。本文将介绍如何使用Python实现自动化的Word排版,让文档编辑变得更加高效便捷。

一、导入必要的库

在Python中,我们可以使用python-docx库来操作Word文档。它提供了丰富的函数和方法,用于创建、修改和格式化Word文档。我们可以通过以下代码导入python-docx库:

import docx

二、打开Word文档

首先,我们需要打开要进行排版的Word文档。可以使用python-docx库提供的`Document`类来打开现有的文档。

 打开Word文档:

doc = docx.Document('example.docx')

三、自动化排版

接下来,我们将使用python-docx库提供的功能来实现自动化的Word排版。以下是一些常见的排版操作示例:

1. 设置页面大小和边距:

doc.sections[0].page_width = docx.shared.Inches(8.5)
doc.sections[0].page_height = docx.shared.Inches(11)
doc.sections[0].left_margin = docx.shared.Inches(1)
doc.sections[0].right_margin = docx.shared.Inches(1)
doc.sections[0].top_margin = docx.shared.Inches(1)
doc.sections[0].bottom_margin = docx.shared.Inches(1)

2. 插入标题:

doc.add_heading('自动化Word排版', level=1)

3. 插入段落:

doc.add_paragraph('在今天的文章中,我们将介绍如何使用Python实现自动化的Word排版。')

4. 设置字体样式:

paragraph = doc.add_paragraph()
run = paragraph.add_run('这是一个示例文本。')
font = run.font
font.name = 'Arial'
font.size = docx.shared.Pt(12)
font.bold = True

5. 插入图片:

doc.add_picture('example.jpg', width=docx.shared.Inches(4), height=docx.shared.Inches(3))

四、保存并关闭文档

完成排版后,我们需要保存并关闭文档。

1. 保存文档:

doc.save('formatted_example.docx')

2. 关闭文档:

doc.close()

五、总结

通过使用Python的python-docx库,我们可以轻松地实现自动化的Word排版。通过打开文档、进行自动化排版操作,以及保存并关闭文档,我们能够提升文档编辑的效率和质量。

参考代码:

import docx
doc = docx.Document('example.docx')
# 自动化排版操作示例
doc.sections[0].page_width = docx.shared.Inches(8.5)
doc.sections[0].page_height = docx.shared.Inches(11)
doc.sections[0].left_margin = docx.shared.Inches(1)
doc.sections[0].right_margin = docx.shared.Inches(1)
doc.sections[0].top_margin = docx.shared.Inches(1)
doc.sections[0].bottom_margin = docx.shared.Inches(1)
doc.add_heading('自动化Word排版', level=1)
doc.add_paragraph('在今天的文章中,我们将介绍如何使用Python实现自动化的Word排版。')
paragraph = doc.add_paragraph()
run = paragraph.add_run('这是一个示例文本。')
font = run.font
font.name = 'Arial'
font.size = docx.shared.Pt(12)
font.bold = True
doc.add_picture('example.jpg', width=docx.shared.Inches(4), height=docx.shared.Inches(3))
# 保存并关闭文档
doc.save('formatted_example.docx')
doc.close()

六、方法补充

用Python编写的Word一键排版工具

import docx
from docx.oxml.ns import qn
from docx.shared import Pt, Cm, Mm
from docx.enum.text import *
import os
import sys
from docx import Document
from PyQt5.QtWidgets import QApplication, QFileDialog
# 删除段落
def delete_paragraph(paragraph):
    p = paragraph._element
    p.getparent().remove(p)
# p._p = p._element = None
    paragraph._p = paragraph._element = None
 
#判断是否为落款格式
def LuoKuan(str):
    for i in str:
        if i in punc:
            return False
    if ((str[0] in num) and (str[-1] == "日") and (len(str) <= 12)) or ((str[0] in cn_num) and (str[-1] == "日") and (len(str) <= 12)):
        return True
    else:
        return False
def setMargin(docx):
    section = docx.sections[0]
    section.page_height = Cm(29.7)
    section.page_width = Cm(21.0)
    section.left_margin = Cm(2.8)
    section.right_margin = Cm(2.6)
    section.top_margin = Cm(3.7)
    section.bottom_margin = Cm(3.5)
 
#判断是否为一级标题格式(如:一、xxx)
def GradeOneTitle(str):
    if ((str[0] in cn_num) and (str[1] == "、")) or ((str[0] in cn_num) and (str[1] in cn_num) and (str[2] == "、")):
        return True
    else:
        return False
 
#判断是否为二级标题格式(如:(一)xxx)
def GradeTwoTitle(str):
    if ((str[0] == "(") and (str[1] in cn_num) and (str[2] == ")")) or ((str[0] == "(") and (str[1] in cn_num) and (str[2] in cn_num) and (str[3] == ")")):
        return True
    else:
        return False
#判断是否为三级标题格式(如:1.xxx)
def GradeThreeTitle(str):
    if ((str[0] in num) and (str[1] in punc)) or ((str[0] in num) and (str[1] in num) and (str[2] in punc)):
        return True
    else:
        return False
#判断是否为四级标题格式(如:(1)xxx)
def GradeFourTitle(str):
    if ((str[0] == "(") and (str[1] in num) and (str[2] == ")")) or ((str[0] == "(") and (str[1] in num) and (str[2] in num) and (str[3] == ")")):
        return True
    else:
        return False
 
#判断是否为五级标题格式(如:一是XXX)
def GradeFiveTitle(str):
    if ((str[0] in cn_num) and (str[1] in must)) or ((str[0] in cn_num) and (str[1] in cn_num) and (str[1] in must)):
        return True
    else:
        return False
 
def OneKeyWord():
    global cn_num,num,punc,must
    cn_num = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"]
    num = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
    punc = ["。", ",", "!", "?", ":", ";", "、", ".", "(", ")","."]
    must = ["要", "是", "能"]
    filecnt = 0
    print('欢迎使用Word一键排版工具!创作者QQ:124500535')
    confirm= input("是否打开Word文档?输入“Y”表示“打开”,输入“N”表示“取消”!")
    if confirm == 'Y' or confirm == 'y':
        a = QApplication([''])
        files, stylel = QFileDialog.getOpenFileNames(caption="多文件选择", directory="/", filter="Word 文档(*.docx)")
        print(files)  # 打印所选文件全部路径(包括文件名和后缀名)和文件类型
        for file in files:
            docx = Document(file)
            paragraphcnt = 0
            filecnt= filecnt+1
            print('这是第%s个文件:%s' %(filecnt,file))
            for paragraph in docx.paragraphs:
                paragraphcnt = paragraphcnt +1
                paragraph.text=paragraph.text.replace(",",",")
                paragraph.text=paragraph.text.replace(";",";")
                paragraph.text=paragraph.text.replace(":",":")
                paragraph.text=paragraph.text.replace("!","!")
                paragraph.text=paragraph.text.replace("?","?")
                paragraph.text=paragraph.text.replace("(","(")
                paragraph.text=paragraph.text.replace(")",")")
                paragraph.text=paragraph.text.replace(" ","")
                paragraph.text=paragraph.text.replace("\t", "")
                paragraph.text = paragraph.text.replace("\n", "")
                if paragraph.text == '':
                    delete_paragraph(paragraph)
                    paragraphcnt = paragraphcnt-1
                    continue
                paragraph.paragraph_format.left_indent = 0  #预先对缩进赋值, 防止对象为空报错
                paragraph.paragraph_format.element.pPr.ind.set(qn("w:firstLineChars"), '0')  #并去除缩进
                paragraph.paragraph_format.element.pPr.ind.set(qn("w:firstLine"), '0')
                paragraph.paragraph_format.element.pPr.ind.set(qn("w:leftChars"), '0')
                paragraph.paragraph_format.element.pPr.ind.set(qn("w:left"), '0')
                paragraph.paragraph_format.element.pPr.ind.set(qn("w:rightChars"), '0')
                paragraph.paragraph_format.element.pPr.ind.set(qn("w:right"), '0')
                print('这是第%s段' %paragraphcnt)
                print(paragraph.text)
                if paragraphcnt == 1 and len(paragraph.text)<40:
                    #处理头部空行
                    #标题(方正小标宋_GBK、2号、加粗、居中、下端按2号字空一行)
                    paragraph.paragraph_format.line_spacing=Pt(28)  #行距固定值28磅
                    paragraph.paragraph_format.space_after = Pt(0)  #段后间距=0
                    for run in paragraph.runs:
                        run.font.size = Pt(22)  # 字体大小2号
                        run.bold = False  # 加粗
                        run.font.name = '方正小标宋_GBK'  # 控制是西文时的字体
                        run.element.rPr.rFonts.set(qn('w:eastAsia'), '方正小标宋_GBK')  # 控制是中文时的字体
                        paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER # 居中
                    continue
                elif paragraphcnt == 2 and len(paragraph.text) < 30:
                    # 作者单位、姓名
                    paragraph.paragraph_format.line_spacing = Pt(28)  # 行距固定值28磅
                    paragraph.paragraph_format.space_after = Pt(0)  # 段后间距=0
                    for run in paragraph.runs:
                        run.font.size = Pt(16)  # 字体大小2号
                        run.bold = False  # 加粗
                        run.font.name = '楷体'  # 控制是西文时的字体
                        run.element.rPr.rFonts.set(qn('w:eastAsia'), '楷体')  # 控制是中文时的字体
                        paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER  # 居中
                    continue
                elif paragraphcnt == 3 and len(paragraph.text) < 30 and (paragraph.text[0] == "(") and (paragraph.text[1] in num):
                    # 日期,如(2023年6月15日)
                    paragraph.paragraph_format.line_spacing = Pt(28)  # 行距固定值28磅
                    paragraph.paragraph_format.space_after = Pt(0)  # 段后间距=0
                    for run in paragraph.runs:
                        run.font.size = Pt(16)  # 字体大小2号
                        run.bold = False  # 加粗
                        run.font.name = '楷体'  # 控制是西文时的字体
                        run.element.rPr.rFonts.set(qn('w:eastAsia'), '楷体')  # 控制是中文时的字体
                        paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER  # 居中
                    continue
                    # #处理正文
                else:
                    paragraph.paragraph_format.line_spacing = Pt(28)  # 行距固定值28磅
                    paragraph.paragraph_format.space_after = Pt(0)  # 段后间距=0
                    paragraph.paragraph_format.first_line_indent = Pt(32)
                    for run in paragraph.runs:
                        run.font.size = Pt(16)  # 字体大小3号
                        run.bold = False  # 字体不加粗
                        run.font.name = '仿宋_GB2312'
                        run.element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
                        if GradeOneTitle(run.text): #判断是否为一级标题格式(如:一、xxx)
                            run.font.name = '黑体'
                            run.element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')
                        elif GradeTwoTitle(run.text): #判断是否为二级标题格式(如:(一)xxx)
                            if "。" not in run.text:
                                run.font.name = '楷体'
                                run.element.rPr.rFonts.set(qn('w:eastAsia'), '楷体')
                            else:
                                run.text = run.text.split('。',1)
                                run.font.name = '楷体'
                                run.element.rPr.rFonts.set(qn('w:eastAsia'), '楷体')
                        elif GradeThreeTitle(run.text): #判断是否为三级标题格式(如:1.xxx)
                            if "。" not in run.text:
                                if (run.text[0] in num) and (run.text[1] in punc):
                                    run.text = run.text.replace(run.text[1], ".",1)
                                if (run.text[0] in num) and (run.text[1] in num) and (run.text[2] in punc):
                                    run.text = run.text.replace(run.text[2], ".", 1)
                                run.font.name = '仿宋_GB2312'
                                run.element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
                                run.bold = True  # 字体加粗
                            else:
                                if (run.text[0] in num) and (run.text[1] in punc):
                                    run.text = run.text.replace(run.text[1], ".", 1)
                                if (run.text[0] in num) and (run.text[1] in num) and (run.text[2] in punc):
                                    run.text = run.text.replace(run.text[2], ".", 1)
                                sentence_to_bold = run.text.split('。')[0]+"。"
                                sentence_not_to_bold = run.text.split('。',1)[1]
                                paragraph.insert_paragraph_before(sentence_to_bold)
                                docx.paragraphs[paragraphcnt - 1].paragraph_format.first_line_indent = Pt(32)
                                docx.paragraphs[paragraphcnt - 1].paragraph_format.line_spacing = Pt(28)  # 行距固定值28磅
                                docx.paragraphs[paragraphcnt - 1].paragraph_format.space_after = Pt(0)  # 段后间距=0
                                docx.paragraphs[paragraphcnt - 1].runs[0].font.name = '仿宋_GB2312'
                                docx.paragraphs[paragraphcnt - 1].runs[0].font.size = Pt(16)  # 字体大小3号
                                docx.paragraphs[paragraphcnt - 1].runs[0].element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
                                docx.paragraphs[paragraphcnt - 1].runs[0].bold = True  # 字体加粗
                                docx.paragraphs[paragraphcnt - 1].add_run(sentence_not_to_bold).bold = False
                                docx.paragraphs[paragraphcnt - 1].runs[1].font.name = '仿宋_GB2312'
                                docx.paragraphs[paragraphcnt - 1].runs[1].font.size = Pt(16)  # 字体大小3号
                                docx.paragraphs[paragraphcnt - 1].runs[1].element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
                                delete_paragraph(paragraph)
                        elif GradeFourTitle(run.text): #判断是否为四级标题格式(如:(1)xxx)
                            if "。" not in run.text:
                                run.font.name = '仿宋_GB2312'
                                run.element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
                                run.bold = True  # 字体加粗
                            else:
                                sentence_to_bold = run.text.split('。')[0]+"。"
                                sentence_not_to_bold = run.text.split('。',1)[1]
                                paragraph.insert_paragraph_before(sentence_to_bold)
                                docx.paragraphs[paragraphcnt - 1].paragraph_format.first_line_indent = Pt(32)
                                docx.paragraphs[paragraphcnt - 1].paragraph_format.line_spacing = Pt(28)  # 行距固定值28磅
                                docx.paragraphs[paragraphcnt - 1].paragraph_format.space_after = Pt(0)  # 段后间距=0
                                docx.paragraphs[paragraphcnt - 1].runs[0].font.name = '仿宋_GB2312'
                                docx.paragraphs[paragraphcnt - 1].runs[0].font.size = Pt(16)  # 字体大小3号
                                docx.paragraphs[paragraphcnt - 1].runs[0].element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
                                docx.paragraphs[paragraphcnt - 1].runs[0].bold = True  # 字体加粗
                                docx.paragraphs[paragraphcnt - 1].add_run(sentence_not_to_bold).bold = False
                                docx.paragraphs[paragraphcnt - 1].runs[1].font.name = '仿宋_GB2312'
                                docx.paragraphs[paragraphcnt - 1].runs[1].font.size = Pt(16)  # 字体大小3号
                                docx.paragraphs[paragraphcnt - 1].runs[1].element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
                                delete_paragraph(paragraph)
                        elif GradeFiveTitle(run.text): #判断是否为五级标题格式(如:一是xxx)
                            if "。" not in run.text:                                
                                run.font.name = '仿宋_GB2312'
                                run.element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
                                run.bold = True  # 字体加粗
                            else:                                
                                sentence_to_bold = run.text.split('。')[0]+"。"
                                sentence_not_to_bold = run.text.split('。',1)[1]
                                paragraph.insert_paragraph_before(sentence_to_bold)
                                docx.paragraphs[paragraphcnt - 1].paragraph_format.first_line_indent = Pt(32)
                                docx.paragraphs[paragraphcnt - 1].paragraph_format.line_spacing = Pt(28)  # 行距固定值28磅
                                docx.paragraphs[paragraphcnt - 1].paragraph_format.space_after = Pt(0)  # 段后间距=0
                                docx.paragraphs[paragraphcnt - 1].runs[0].font.name = '仿宋_GB2312'
                                docx.paragraphs[paragraphcnt - 1].runs[0].font.size = Pt(16)  # 字体大小3号
                                docx.paragraphs[paragraphcnt - 1].runs[0].element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
                                docx.paragraphs[paragraphcnt - 1].runs[0].bold = True  # 字体加粗
                                docx.paragraphs[paragraphcnt - 1].add_run(sentence_not_to_bold).bold = False
                                docx.paragraphs[paragraphcnt - 1].runs[1].font.name = '仿宋_GB2312'
                                docx.paragraphs[paragraphcnt - 1].runs[1].font.size = Pt(16)  # 字体大小3号
                                docx.paragraphs[paragraphcnt - 1].runs[1].element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
                                delete_paragraph(paragraph)
                        elif LuoKuan(run.text):  # 判断是否为落款格式
                            run.font.name = '仿宋_GB2312'
                            run.element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
                            run.text = "\r" * 2 + run.text  # 前置空格,顶到最右,需手动调整空格
                            paragraph.paragraph_format.left_indent = Pt(288)    #18B*16Pt=288Pt
                        else: #普通正文格式
                            run.font.name = '仿宋_GB2312'
                            run.element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
            setMargin(docx)
            docx.save(file)
if __name__ == '__main__':
    OneKeyWord()
    os.system("pause")

到此这篇关于Python实现自动化Word排版的文章就介绍到这了,更多相关Python Word排版内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python实现的单向循环链表功能示例

    Python实现的单向循环链表功能示例

    这篇文章主要介绍了Python实现的单向循环链表功能,简单描述了单向循环链表的概念、原理并结合实例形式分析了Python定义与使用单向循环链表的相关操作技巧,需要的朋友可以参考下
    2017-11-11
  • 深度剖析使用python抓取网页正文的源码

    深度剖析使用python抓取网页正文的源码

    平时打开一个网页,除了文章的正文内容,通常会有一大堆的导航,广告和其他方面的信息。本文的目的,在于说明如何从一个网页中提取出文章的正文内容,而过渡掉其他无关的的信息。
    2014-06-06
  • 使用Python操作Excel中的各项页面设置功能

    使用Python操作Excel中的各项页面设置功能

    在使用Excel进行数据分析或报告制作时,页面设置是确保最终输出效果专业、美观的关键步骤,合理的页面设置不仅能够优化打印效果,还能提升数据的可读性,本文将详细介绍如何使用Python操作Excel中的各项页面设置功能,需要的朋友可以参考下
    2024-08-08
  • python matplotlib绘图过程中设置线条颜色实战举例

    python matplotlib绘图过程中设置线条颜色实战举例

    Matplotlib是一个用于数据可视化和创建交互式图表的Python库,下面这篇文章主要给大家介绍了关于python matplotlib绘图过程中设置线条颜色的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-05-05
  • Python给对象数组排序的方法实现

    Python给对象数组排序的方法实现

    本文主要介绍了Python给对象数组排序的方法实现,可以使用sorted()函数或list.sort()方法来对对象数组按照第二个值进行排序,具有一定的参考价值,感兴趣的可以了解一下
    2025-03-03
  • 运筹学-Python实现图论与最短距离

    运筹学-Python实现图论与最短距离

    需要求解任意两个节点之间的最短距离,使用 Floyd 算法,只要求解单源最短路径问题,有负权边时使用 Bellman-Ford 算法,没有负权边时使用 Dijkstra 算法,本节我们只讨论Dijkstra 算法,需要的朋友可以参考一下
    2022-01-01
  • PyQt5基本控件使用详解:单选按钮、复选框、下拉框

    PyQt5基本控件使用详解:单选按钮、复选框、下拉框

    这篇文章主要介绍了PyQt5基本控件使用:单选按钮、复选框、下拉框,本文中的内容和实例也基本回答了开篇提到的问题。需要的朋友可以参考下
    2019-08-08
  • Python中TypeError: int object is not iterable错误分析及解决办法

    Python中TypeError: int object is not 

    在Python中,当你尝试对一个非迭代对象(如整数、浮点数等)使用迭代操作(如for循环、列表推导式中的迭代等)时,会触发TypeError: 'int' object is not iterable错误,所以本文给大家介绍了Python中TypeError: int object is not iterable错误分析及解决办法
    2024-08-08
  • 强悍的Python读取大文件的解决方案

    强悍的Python读取大文件的解决方案

    今天小编就为大家分享一篇关于强悍的Python读取大文件的解决方案,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-02-02
  • Python各种类型装饰器详细介绍

    Python各种类型装饰器详细介绍

    大家好,本篇文章主要讲的是Python各种类型装饰器详细介绍,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下,方便下次浏览
    2021-12-12

最新评论