Python处理word的常用操作详解

Python 处理 Word 文档通常使用 python-docx 库。以下是一些常用的操作和相应的代码示例:

这些是使用 python-docx 库处理 Word 文档时的一些常用操作。根据你的具体需求,可能还需要探索更多的功能和方法。在使用这些功能之前,请确保已经安装了 python-docx 库:

pip install python-docx
  1. 创建一个新的 Word 文档
    使用 Document 类可以创建一个新的 Word 文档。

    from docx import Document
    
    doc = Document()
    doc.add_paragraph('Hello, World!')
    doc.save('new_document.docx')
    
  2. 读取现有的 Word 文档
    使用 Document 类也可以打开现有的 Word 文档。

    doc = Document('existing_document.docx')
    for para in doc.paragraphs:
        print(para.text)
    
  3. 添加段落
    使用 add_paragraph 方法可以向文档中添加新的段落。

    doc.add_paragraph('This is a new paragraph.')
    
  4. 设置段落格式
    使用 Paragraph 对象的属性可以设置段落的格式。

    from docx.shared import Pt
    from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
    
    para = doc.add_paragraph('This is a centered paragraph.')
    para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    para.space_after = Pt(12)
    
  5. 添加文本到现有段落
    使用 add_run 方法可以向现有段落添加文本。

    para.add_run(' This is additional text in the same paragraph.')
    
  6. 设置字体样式
    使用 add_run 方法并设置 Run 对象的属性可以设置文本的样式。

    from docx.shared import RGBColor
    
    run = para.add_run('This text is bold and italic.')
    run.bold = True
    run.italic = True
    run.font.color.rgb = RGBColor(255, 0, 0)  # Red color
    
  7. 添加图片
    使用 add_picture 方法可以向文档中添加图片。

    doc.add_picture('image.jpg', width=Inches(2.5))
    
  8. 添加表格
    使用 add_table 方法可以向文档中添加表格。

    table = doc.add_table(rows=2, cols=2)
    hdr_cell_width = Inches(4)
    for i in range(2):
        for j in range(2):
            cell = table.cell(i, j)
            cell.width = hdr_cell_width
            cell.text = f'Row {i + 1}, Column {j + 1}'
    
  9. 设置页面布局
    使用 Section 对象可以设置页面布局。

    from docx.shared import Pt
    from docx.oxml.ns import qn
    
    section = doc.sections[0]
    section.orientation = WD_ORIENTATION.PORTRAIT
    section.page_width = Pt(8.5)
    section.page_height = Pt(11)
    section.top_margin = Pt(1)
    section.bottom_margin = Pt(1)
    section.left_margin = Pt(1)
    section.right_margin = Pt(1)
    
  10. 保存文档
    使用 save 方法可以保存文档。

    doc.save('modified_document.docx')
    
  11. 遍历文档内容
    使用循环可以遍历文档中的所有段落、表格等。

    for element in doc.element.body:
        if isinstance(element, OxmlElement) and element.tag.endswith('p'):
            print(element.text)
    
  12. 替换文本
    使用 document.replace_text 方法可以替换文档中的文本。

    from docx.document import Document as _Document
    _Document.replace_text(doc.element.body, 'old_text', 'new_text')
    
  13. 添加页眉和页脚
    使用 headerfooter 属性可以添加页眉和页脚。

    header = doc.sections[0].header
    p = header.add_paragraph()
    p.add_run('This is the header.')
    
    footer = doc.sections[0].footer
    p = footer.add_paragraph()
    p.add_run('This is the footer.')
    
  14. 添加目录
    使用 add_table_of_contents 方法可以添加目录。

    doc.add_table_of_contents(title='Table of Contents')
    
  15. 添加页码
    使用 add_page_numbers 方法可以添加页码。

    doc.sections[0].footer.add_page_numbers()
    
  16. 添加超链接
    使用 add_hyperlink 方法可以添加超链接。

    para = doc.add_paragraph()
    run = para.add_run('This is a hyperlink.')
    run.add_hyperlink('http://www.example.com', 'Click here')
    
  17. 添加书签和交叉引用
    使用 add Bookmarkadd_cross_reference 方法可以添加书签和交叉引用。

    bookmark = doc.add_bookmark('myBookmark', doc.paragraphs[0])
    para = doc.add_paragraph('This is a reference to bookmark.')
    para.add_run().add_cross_reference('myBookmark')
    
  18. 设置文档属性
    使用 coreproperties 模块可以设置文档的元数据。

    from docx.opc.constants import RELATIONSHIP_TYPE as RT
    from docx.oxml.shared import qn
    from docx.oxml.ns import qn
    
    properties = doc.core_properties
    properties.title = 'My Document'
    properties.subject = 'Python Docx'
    properties.author = 'Author Name'
    
  19. 设置段落样式
    使用预定义的样式可以快速设置段落的格式。

    from docx.shared import Pt
    from docx.enum.style import WD_STYLE_TYPE
    
    styles = doc.styles
    heading_style = styles['Heading 1']
    para_style = styles['Normal']
    
    doc.add_paragraph('This is a heading.', style=heading_style)
    doc.add_paragraph('This is a normal paragraph.', style=para_style)
    
  20. 添加列表
    使用 add_list 方法可以向文档中添加有序或无序的列表。

    from docx.oxml.ns import qn
    from docx.oxml import OxmlElement
    
    list_item_tags = (qn('w:p'), qn('w:r'), qn('w:t'))
    list_item = OxmlElement('w:p')
    list_item.text = 'List item text'
    
    run = list_item.xpath('.//'.join(list_item_tags))[0]
    run.rPr = OxmlElement('w:rPr')
    run.rPr.val = OxmlElement('w:numPr')
    run.rPr.val.add_namespacedecls({
        'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
        'num': 'http://schemas.openxmlformats.org/wordprocessingml/2006/numbering'
    })
    doc.add_list_item(list_item)
    
  21. 添加页眉和页脚到所有页面
    使用 headerfooter 属性可以为文档的所有页面设置页眉和页脚。

    header = doc.sections[0].header
    header.add_paragraph('Header for all pages.')
    
    footer = doc.sections[0].footer
    footer.add_paragraph('Footer for all pages.')
    
  22. 设置文档的页边距
    使用 page_margins 方法可以设置文档的页边距。

    from docx.shared import Inches
    
    for section in doc.sections:
        section.left_margin = Inches(1)
        section.right_margin = Inches(1)
        section.top_margin = Inches(1)
        section.bottom_margin = Inches(1)
    
  23. 设置文档的分栏
    使用 set_landscape 方法和 set_evenly_spread 属性可以设置文档的分栏。

    for section in doc.sections:
        section.set_landscape(True)
        section.set_evenly_spread(True)
        section.column_count = 3
    
  24. 添加水印
    使用 add_watermark 方法可以向文档中添加水印。

    from docx.shared import Pt
    from docx.oxml.ns import qn
    
    doc.add_watermark('Confidential', font_size=Pt(18), color='gray')
    
  25. 添加文档的页码格式
    使用 add_page_numbers 方法可以设置文档的页码格式。

    from docx.shared import Pt
    
    for section in doc.sections:
        page_number = section.footer.add_page_numbers()
        page_number.font.size = Pt(12)
    
  26. 添加文档的页码范围
    使用 add_page_numbers 方法可以设置文档的起始页码。

    from docx.shared import Pt
    
    for section in doc.sections:
        page_number = section.footer.add_page_numbers(start=2)
        page_number.font.size = Pt(12)
    
  27. 添加文档的页码到页眉
    使用 add_run 方法可以向页眉中添加页码。

    for section in doc.sections:
        header = section.header
        para = header.paragraphs[0]
        run = para.add_run()
        run.add_text('Page ')
        run.add_page_number().rtl = True
    
  28. 添加文档的目录
    使用 add_table_of_contents 方法可以向文档中添加目录。

    doc.add_table_of_contents(title='Table of Contents', style='TOC Heading')
    
  29. 添加文档的交叉引用
    使用 add_cross_reference 方法可以向文档中添加交叉引用。

    bookmark = doc.add_bookmark('BookmarkName', doc.paragraphs[0])
    run = para.add_run()
    run.add_cross_reference('BookmarkName', 'Bookmark Text')
    
  30. 添加文档的脚注和尾注
    使用 add_footnoteadd_endnote 方法可以向文档中添加脚注和尾注。

    para = doc.add_paragraph('This is a paragraph with a footnote.')
    para.add_run('A footnote text.').add_footnote('This is the footnote text.')
    
    para = doc.add_paragraph('This is a paragraph with an endnote.')
    para.add_run('An endnote text.').add_endnote('This is the endnote text.')
    
  31. 添加文档的自定义属性
    使用 add_custom_xml_part 方法可以向文档中添加自定义 XML 属性。

    from docx.opc.custom_xml_part import CustomXmlPart
    
    custom_xml = '<root><element key="value">Text</element></root>'
    part = docx.add_custom_xml_part(custom_xml)
    print(part.uri)
    
  32. 添加文档的大纲级别
    使用 outline_level 属性可以设置文档的大纲级别。

    para = doc.add_paragraph('This is a paragraph with outline level.')
    run = para.add_run('This is the run text.')
    run.outline_level = 1
    
  33. 添加文档的评论
    使用 add_comment 方法可以向文档中添加评论。

    from datetime import datetime
    
    comment = doc.add_comment('Comment text', 'Comment Author', datetime.now())
    
  34. 添加文档的修订跟踪
    使用 add_paragraph 方法时设置 track_revisions 属性可以开启修订跟踪。

    doc.track_revisions = True
    para = doc.add_paragraph('This is a paragraph with revision tracking.')
    
  35. 添加文档的密码保护
    使用 protect 方法可以为文档添加密码保护。

    from docx.opc.constants import DOCUMENT_PROTECTION_TYPE
    
    doc.protect(protection_type=DOCUMENT_PROTECTION_TYPE.FORM_FILLING)
    
  36. 修改文档的样式
    可以创建或修改样式,然后应用到文档的段落或文本上。

    from docx.shared import Pt
    from docx.enum.style import WD_STYLE_TYPE
    
    style = doc.styles.add_style('My Style', WD_STYLE_TYPE.PARAGRAPH)
    style.font.size = Pt(24)
    style.font.bold = True
    style.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    
    para = doc.add_paragraph('This text uses my custom style.')
    para.style = 'My Style'
    
  37. 处理文档的节
    可以添加或修改文档的节(sections)来控制页面布局和格式。

    from docx.oxml.ns import qn
    from docx.oxml import OxmlElement
    
    new_section = doc.add_section()
    new_section.start_type = WD_SECTION_START.NEW_PAGE
    new_section.page_width = Inches(8.5)
    new_section.page_height = Inches(11)
    
  38. 使用域代码
    可以插入和操作 Word 的域代码(field codes),例如插入时间或日期。

    from docx.enum.field import WD_FIELD_TYPE
    
    run = para.add_run()
    run.add_field('DATE', 'DATE \@ "MM/DDD/YYYY"', None)
    
  39. 处理文档的批注
    可以添加、编辑或删除文档的批注(comments)。

    from docx.oxml.ns import qn
    from docx.oxml.shared import qn as qn_
    from docx.oxml.xmlchemy import OxmlElement
    
    comment_author = 'Author Name'
    comment_date = '2024-06-28T12:00:00'
    comment_text = 'This is a comment.'
    
    comment_elem = OxmlElement('w:comment')
    comment_elem.set(qn_('w:author'), comment_author)
    comment_elem.set(qn_('w:date'), comment_date)
    comment_elem.set(qn_('w:text'), comment_text)
    
    run = para.add_run()
    run.add_comment(comment_elem)
    
  40. 处理文档的修订
    可以添加、接受或拒绝文档的修订。

    from docx.shared import RGBColor
    from docx.enum.text import WD_COLOR_INDEX
    
    run = doc.add_paragraph('This is a revised text.').add_run()
    run.bold = True
    run.revision_id = 1
    run.author = 'Author Name'
    run.date = '2024-06-28T12:00:00'
    run.revision_type = WD_REVISION_TYPE.INSERTION
    run.font.color.rgb = RGBColor(255, 0, 0)  # Red color
    
  41. 处理文档的大纲级别
    可以设置段落的大纲级别,用于创建目录。

    from docx.enum.list import WD_OUTLINE_LEVEL
    
    para = doc.add_paragraph('Heading 1')
    para.style = 'Heading 1'
    para_outline_level = para.paragraph_format-outline_level
    para_outline_level.val = WD_OUTLINE_LEVEL.LEVEL1
    
  42. 处理文档的超链接
    可以添加、编辑或删除文档的超链接。

    from docx.oxml.ns import qn
    from docx.oxml.shared import qn as qn_
    
    hyperlink = doc.add_hyperlink('http://www.example.com', 'Click here')
    hyperlink.rel = 'external'
    hyperlink.target_mode = 'External'
    
  43. 处理文档的自定义XML
    可以添加或修改文档的自定义XML部分。

    from docx.opc.custom_xml_part import CustomXmlPart
    
    custom_xml = '<root><element key="value">Text</element></root>'
    custom_xml_part = docx.add_custom_xml_part(custom_xml)
    
  44. 处理文档的属性
    可以添加或修改文档的核心属性。

    from docx.shared import Pt
    from docx.opc.constants import RELATIONSHIP_TYPE as RT
    
    properties = doc.core_properties
    properties.title = 'My Document'
    properties.subject = 'Python Docx'
    properties.author = 'Author Name'
    properties.last_modified_by = 'Author Name'
    properties.revision = 1
    properties.version = 1
    
  45. 处理文档的安全性
    可以设置文档的密码和加密类型。

    from docx.opc.package import Package
    
    package = Package(doc.path)
    package.part_related_settings.restrict_edition = True
    package.part_related_settings.permit_form_filling = True
    package.save()
    

请注意,python-docx 库不支持所有 Word 功能,一些高级操作可能需要使用其他库或通过 Word 宏来实现。此外,某些操作可能需要对 OpenXML 格式有较深的理解。如果 python-docx 库的功能不能满足需求,可以考虑使用其他库,如 pywin32(仅限 Windows)来与 Word 应用程序进行交互。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/767501.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

游戏冻结工具 -- 雪藏HsFreezer v1.78

软件简介 HsFreezer是一款多功能游戏冻结工具&#xff0c;它允许用户随意暂停和继续游戏&#xff0c;同时具备系统优化和进程管理的功能。这款软件特别适合希望在游戏加载时间节省或在游戏与其他任务之间快速切换的用户。其主要特点包括快捷键操作、单锁模式的丝滑切换&#x…

湖北建筑安全员A证跨省调出审核不通过?可能是这些原因

湖北建筑安全员A证跨省调出审核不通过&#xff1f;可能是这些原因 湖北建筑安全员A证跨省调出审核不通过怎么办&#xff1f; 湖北建筑安全员ABC正常情况下都是可以跨省调出的&#xff0c;现在建筑三类人员安全员ABC在全国工程质量安全监管信息平台都是可以查询的&#xff0c;在…

《中国化工贸易》是什么级别的期刊?是正规期刊吗?能评职称吗?

​问题解答 问&#xff1a;《中国化工贸易》是不是核心期刊&#xff1f; 答&#xff1a;不是&#xff0c;是知网收录的第一批认定学术期刊。 问&#xff1a;《中国化工贸易》级别&#xff1f; 答&#xff1a;国家级。主管单位&#xff1a;中国石油和化学工业联合会 主办单…

据阿谱尔统计,全球mRNA原料酶市场预计2024年达到11.98亿美元

Codexis 宣布与 Aldevron 达成协议&#xff0c;授予 Aldevron Codexis 的 Codex HiCap RNA 聚合酶的全球制造和商业化权利。 Applied DNA、Maravai LifeSciences (MRVI) 和 Alphazyme 达成协议&#xff0c;Alphazyme 将扩大 Applied DNA 专有 Linea™ RNA 聚合酶 (RNAP) 的生产…

图书管理系统(含登录验证码操作)

文章目录 登录需求分析登录界面注册功能&#xff1a;登录功能&#xff1a;忘记密码&#xff1a;验证码规则&#xff1a; 图书管理系统需求Book包Book类BookList类 IOperation包IOperation接口查找图书新增图书删除图书显示图书借阅图书归还图书退出系统 User包user类Users类adm…

干货分享|如何将前端代理服务器(BFF)接入身份认证(3完结篇)

续集3 前篇文章在前面发布&#xff0c;同学们可以自行找一下。 本篇文章将继续通过实例来详细讲解如何将前端代理服务器&#xff08;BFF&#xff09;接入身份认证。我们将使用一个示例应用来演示 BFF 与身份认证的集成过程。 3 在 Full BFF 中接入认证平台 本小节将介绍如何…

矢量绘图设计Sketch中文 Sketch直装安装包

Sketch是一款专为UI设计师和UX专家打造的矢量图形设计软件&#xff0c;以其简洁的界面、强大的功能和高效的协作能力而闻名。Sketch支持快速创建高质量的UI界面、图标、图形和插画&#xff0c;其矢量绘图工具让设计细节更加精准。同时&#xff0c;Sketch内置丰富的插件和组件库…

设计模式-结构型-08-组合模式

文章目录 1、学校院系展示需求2、组合模式基本介绍3、组合模式示例3.1、 解决学校院系展示&#xff08;透明模式1&#xff09;3.2、高考的科目&#xff08;透明模式2&#xff09;3.3、高考的科目&#xff08;安全组合模式&#xff09; 4、JDK 源码分析5、注意事项和细节 1、学校…

MySQL之应用层优化(二)

应用层优化 Web服务器问题 寻找最优并发度 每个Web服务器都有一个最佳并发度——就是说&#xff0c;让进程处理请求尽可能快&#xff0c;并且不超过系统负载的最优的并发连接数。这就是前面说的最大系统容量。进行一个简单的测量和建模&#xff0c;或者只是反复试验&#xf…

Python基础入门知识

目录 引言 简要介绍Python语言 为什么要学习Python Python的应用领域 Python安装和环境配置 Python的下载和安装(Windows, macOS, Linux) 配置Python环境变量 安装和使用IDE(如PyCharm, VS Code) Python基本语法 注释 变量和数据类型(数字,字符串,列表,元组,字典,…

互联网医院系统源码解析:如何打造智能数字药店APP?

在互联网技术飞速发展的今天&#xff0c;医疗行业也在不断与之融合&#xff0c;互联网医院系统应运而生。特别是智能数字药店APP的兴起&#xff0c;使得医疗服务变得更加便捷、高效。本文将深入解析互联网医院系统源码&#xff0c;探讨如何打造一个智能的数字药店APP。 一、互…

思维,CF 739A - Alyona and mex

一、题目 1、题目描述 2、输入输出 2.1输入 2.2输出 3、原题链接 739A - Alyona and mex 二、解题报告 1、思路分析 我们考虑区间mex运算的值最大也就是区间长度&#xff0c;所以我们最大值的上界就是所有区间中的最小长度&#xff0c;假如记为mi 我们一定可以构造出答案…

【C++】const详解

&#x1f4e2;博客主页&#xff1a;https://blog.csdn.net/2301_779549673 &#x1f4e2;欢迎点赞 &#x1f44d; 收藏 ⭐留言 &#x1f4dd; 如有错误敬请指正&#xff01; &#x1f4e2;本文作为 JohnKi &#xff0c;引用了部分大佬的案例 &#x1f4e2;未来很长&#xff0c;…

RabbitMQ 更改服务端口号

需求 windows环境下&#xff0c;将RabbitMQ默认的端口号 5672 改为 11001 实现 本机RabbitMQ版本为3.8.16&#xff0c;找到配置文件位置&#xff0c;路径为&#xff1a;C:\Users\%USERNAME%\AppData\Roaming\RabbitMQ\advanced.config 配置文件默认内容为空 填写修改端口号…

QGC添加添加QML可访问的单例

文章目录 前言一、添加文件二、修改qgroundcontrol.pro三、修改QGCApplication.cc四、修改QGroundControlQmlGlobal.h五、修改QGroundControlQmlGlobal.cc六、测试前言 QGC 4.2 一、添加文件 在src目录下添加文件夹SingletonTest,在里面新建SingletonTest.cc和SingletonTes…

【Sklearn-驯化】一文搞懂很难的EM算法以及实践

【Sklearn-驯化】一文搞懂很难的EM算法以及实践 本次修炼方法请往下查看 &#x1f308; 欢迎莅临我的个人主页 &#x1f448;这里是我工作、学习、实践 IT领域、真诚分享 踩坑集合&#xff0c;智慧小天地&#xff01; &#x1f387; 免费获取相关内容文档关注&#xff1a;微信公…

Unity扩展 Text支持超链接文本

重点提示&#xff1a;当前的文本扩展支持多个超链接&#xff0c;支持修改超链接规则和支持修改超链接颜色。 近期在邮件文本中用到了超链接。最初是在邮件窗口中新加一个按钮用来超链接跳转&#xff0c;之后发现效果表现不如直接在文本中添加&#xff0c;后经过几个小时的资料…

两步解决Hugging Face下载模型速度慢/连接超时/无法下载问题

博主使用的配置是 x86_64 Linux服务器 第一步设置代理镜像: export HF_ENDPOINT=https://hf-mirror.com 第二步(使用代码时,删除引号): --token参数表示下载的模型是否需要登录验证(部分模型需要token) huggingface-cli download --token "获取的hf_*******token…

如何选择优质模型?SD3性能究竟如何?

遇到难题不要怕&#xff01;厚德提问大佬答&#xff01; 厚德提问大佬答12 厚德提问大佬答第十二期 你是否对AI绘画感兴趣却无从下手&#xff1f;是否有很多疑问却苦于没有大佬解答带你飞&#xff1f;从此刻开始这些问题都将迎刃而解&#xff01;你感兴趣的话题&#xff0c;厚德…

vivado联合modelsim仿真

一. 编译Vivado仿真库 打开Vivado&#xff0c;Tools -> Compile Simulation Libraries 二. 设置仿真工具和库路径 因为新建工程的默认仿真工具是Vivado Simulator&#xff0c;所以要使用Modelsim仿真&#xff0c;每个新工程都要设置一次&#xff0c;方法如下&#xff1a; …