• 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 = 'Text'
      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 = 'Text'
      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 应用程序进行交互。

  • 相关阅读:
    分布式架构篇
    【C# 学习笔记 ①】C# 程序结构和基本语法(VSCode工具配置、数据类型、修饰符、构造函数)
    ​软考-高级-信息系统项目管理师教程 第四版【第15章-项目风险管理-思维导图】​
    SwiftUI 4 新功能 之 网格视图Gridview组件 (教程含源码)
    最短路 hdu 2544a
    在Dockerfile中进行apt下载加速
    javaEE Web(Tomcat)深度理解 和 Servlet的本质
    数据库原理及MySQL应用 | 关系规范化
    通过制作llama_cpp的docker镜像在内网离线部署运行大模型
    动作捕捉(Motion Capture)文件BVH的解读笔记
  • 原文地址:https://blog.csdn.net/mj256115/article/details/140036864