Python docx:在Python中创建和操作Word文档

使用docx库,可以执行各种任务

  • 创建新文档:可以使用库从头开始或基于模板生成新的Word文档。这对于自动生成报告、信函和其他类型的文档非常有用。
  • 修改现有文档:可以打开现有的Word文档,并使用库修改其内容、格式、样式等。这对于自动更新遵循特定结构的文档特别方便。
  • 添加内容:可以使用库向文档添加段落、标题、表格、图像和其他元素。这有助于用数据动态填充文档。
  • 格式化:该库允许将各种格式化选项应用于文档中的文本和元素,例如更改字体、颜色、对齐方式等。
  • 提取信息:还可以从现有Word文档中提取文本、图像、表格和其他内容,以便进一步分析

Docx functions

1. 文档创建和保存

  • Document(): 创建一个新的word文档
  • Document.save(‘filename.docx’):保存一个document 称为文件(*.docx)

2. Paragraphs and Text (段落和文本)

  • add_paragraph(‘text’): 添加具有指定文本(text)的新段落(Paragraphs)。
  • paragraph.text:获取或设置段落的文本内容。

3. Headings (标题,可以设置几级标题)

  • add_heading(‘text’, level=n): 添加具有指定文本和级别的标题 (1 to 9).

4. Styles and Formatting (样式与格式)

  • paragraph.style = ‘StyleName’: 应用特定的段落样式
  • run = paragraph.add_run(‘text’): 添加一段具有特定格式的文本
  • run.bold, run.italic, etc.: 对管路(run)应用格式设置

5. Tables (表格操作)

  • add_table(rows, cols): 添加具有指定行数和列数的表
  • table.cell(row, col): 获取表中的特定单元格(cell)
  • cell.text:获取或设置单元格的文本内容
  • table.rows, table.columns:访问表的行和列

6. Images(图片操作)

  • document.add_picture(‘image_path’): 向文档中添加图像
  • run.add_picture(‘image_path’): 将图像添加到特定管道(run)中, 比如简历照片位置固定的

7. Document Properties (文档属性)

  • document.core_properties.title: 设置文档的标题
  • document.core_properties.author: 设置文档的作者
  • document.core_properties.keywords: 设置文档的关键词

8. Sections and Page Setup (分区和页面设置)

  • section = document.sections[0]: 获取文档的第一部分( Get the first section of the document)
  • section.page_width, section.page_height: 设置页面尺寸(Set page dimensions)

9. Lists (列表)

就是markdown中的list,比如下面的这两个就是无序的,大标题1,2,3…就是有序的

  • add_paragraph(‘text’, style=’ListBullet’):创建无序列表( Create a bulleted list)
  • add_paragraph(‘text’, style=’ListNumber’): 创建有序列表(Create a numbered list.)

10. Hyperlinks (超链接)

  • run.add_hyperlink(‘url’, ‘text’): 给当前管道(run)内的特定文本(text)添加超链接(Add a hyperlink to a run)

11. Document Modification (文件修改)

  • document.paragraphs: 访问文档中的所有段落(Access all paragraphs in the document)
  • document.tables: 访问文档中的所有表格(Access all tables in the document)
  • document.styles: 访问和操作文档样式(Access and manipulate document styles)

12. Document Reading(文档读取)

  • Document(‘filename.docx’): 读取一个存在的word文件
  • document.paragraphs[0].text: 访问第一段(paragraphs)的文本(text)

小例子

1. Installation (安装)

pip install python-docx

2. 创建一个新的word文档

创建一个包含文本、标题、表格、图像和格式的文档

  1. Create a new document.(创建一个新的document 对象)
  2. Add a title with centered alignment.(添加一个标题(title)并居中对齐)
  3. Add a paragraph with bold and italic text.(添加带有粗体和斜体文本的段落)
  4. Add a heading and a bulleted list.(添加标题(heading)和项目符号列表)
  5. Add a table with custom column widths.(添加table,并自定义列宽)
  6. Add an image to the document.(添加图片)
  7. Save the document with the name ‘example_document.docx’.(保存文件,文件名为 example_document.docx)
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH

# Create a new document
doc = Document()

# Add a title
title = doc.add_heading('Document Creation Example', level=1)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER

# Add a paragraph with bold and italic text
paragraph = doc.add_paragraph('This is a sample document created using the python-docx library.')
run = paragraph.runs[0]
run.bold = True
run.italic = True

# Add a heading
doc.add_heading('Section 1: Introduction', level=2)

# Add a bulleted list
list_paragraph = doc.add_paragraph()
list_paragraph.add_run('Bullet 1').bold = True
list_paragraph.add_run(' - This is the first bullet point.')
list_paragraph.add_run('\n')
list_paragraph.add_run('Bullet 2').bold = True
list_paragraph.add_run(' - This is the second bullet point.')

# Add a table
doc.add_heading('Section 2: Data', level=2)
table_1 = doc.add_table(rows=1, cols=2)
table_1.style = 'Table Grid'
table_1.autofit = False
table_1.allow_autofit = False
for row in table_1.rows:
    for cell in row.cells:
        cell.width = Pt(150)
table_1.cell(0, 0).text = 'cat'
table_1.cell(0, 1).text = 'dog'

table_2 = doc.add_table(rows=3, cols=3)
table_2.style = 'Table Grid'
table_2.autofit = False
table_2.allow_autofit = False
for row in table_2.rows:
    for cell in row.cells:
        cell.width = Pt(100)
table_2.cell(0, 0).text = 'Name'
table_2.cell(0, 1).text = 'Age'
table_2.cell(0, 2).text = 'City'
for i, data in enumerate([('Alice', '25', 'New York'), ('Bob', '30', 'San Francisco'), ('Charlie', '22', 'Los Angeles')], start=0):
    print(i, data)
    table_2.cell(i, 0).text = data[0]
    table_2.cell(i, 1).text = data[1]
    table_2.cell(i, 2).text = data[2]

# Add an image
doc.add_heading('Section 3: Image', level=2)
doc.add_paragraph('Here is an image of cat:')
doc.add_picture('../imgs/cat.jpg', width=Pt(300))

# Save the document
doc.save('../word_files/example_new_document.docx')

结果(哈哈,样式有点丑,暂时忽略…):

在这里插入图片描述

3. 修改现有的word文档

  1. open an existing Word document (‘existing_document.docx’).( 读取一个存在的word文档)
  2. Modify the text, formatting, and alignment of the first paragraph.(修改第一段的文本、格式和对齐方式)
  3. Add a new heading.(添加一个新的标题)
  4. Add a new paragraph with a hyperlink.(添加带有超链接的新段落)
  5. Add a new table with custom column widths and data.(添加一个具有自定义列宽和数据的新表)
  6. Save the modified document as ‘modified_document.docx’.(将修改后的文档另存为“modified_document.docx”)
import docx
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH

def add_hyperlink(paragraph, url, text, color, underline):
    """
    A function that places a hyperlink within a paragraph object.

    :param paragraph: The paragraph we are adding the hyperlink to.
    :param url: A string containing the required url
    :param text: The text displayed for the url
    :return: The hyperlink object
    """

    # This gets access to the document.xml.rels file and gets a new relation id value
    part = paragraph.part
    r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)

    # Create the w:hyperlink tag and add needed values
    hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
    hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )

    # Create a w:r element
    new_run = docx.oxml.shared.OxmlElement('w:r')

    # Create a new w:rPr element
    rPr = docx.oxml.shared.OxmlElement('w:rPr')

    # Add color if it is given
    if not color is None:
      c = docx.oxml.shared.OxmlElement('w:color')
      c.set(docx.oxml.shared.qn('w:val'), color)
      rPr.append(c)

    # Remove underlining if it is requested
    if not underline:
      u = docx.oxml.shared.OxmlElement('w:u')
      u.set(docx.oxml.shared.qn('w:val'), 'none')
      rPr.append(u)

    # Join all the xml elements together add add the required text to the w:r element
    new_run.append(rPr)
    new_run.text = text
    hyperlink.append(new_run)

    paragraph._p.append(hyperlink)

    return hyperlink
# Open an existing document

doc = Document('../word_files/example_new_document.docx')

# Access the first paragraph and modify its text and formatting
first_paragraph = doc.paragraphs[0]
first_paragraph.text = 'Updated Text: 宫廷玉液酒,一百八一杯。'
run = first_paragraph.runs[0]
run.bold = True #加粗
run.italic = True #斜体
run.font.size = Pt(20) #字号
first_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER #居中对齐

# Add a new heading
doc.add_heading('New Section', level=1)

# Add a new paragraph with a hyperlink
new_paragraph = doc.add_paragraph('Visit my bolg website: ')
hyperlink = add_hyperlink(new_paragraph,
              'https://blog.csdn.net/weixin_40959890/article/details/137598605?spm=1001.2014.3001.5501',
              'Python docx:在Python中创建和操作Word文档',
              'FF8822', True)
# run = new_paragraph.add_run('Python docx:在Python中创建和操作Word文档')
# run.hyperlink.address = 'https://blog.csdn.net/weixin_40959890/article/details/137598605?spm=1001.2014.3001.5501'

# Add a new table
doc.add_heading('Table Section', level=2)
table = doc.add_table(rows=4, cols=4)
table.style = 'Table Grid'
table.autofit = False
table.allow_autofit = False
for row in table.rows:
    for cell in row.cells:
        cell.width = Pt(100)
table.cell(0, 0).text = 'Name'
table.cell(0, 1).text = 'Age'
table.cell(0, 2).text = 'City'
for i, data in enumerate([('David', '128', 'London'), ('Emma', '135', 'New York'), ('John', '122', 'Los Angeles')], start=1):
    table.cell(i, 0).text = data[0]
    table.cell(i, 1).text = data[1]
    table.cell(i, 2).text = data[2]

# Save the modified document
doc.save('../word_files/example_modified_document.docx')
结果看一下(依旧很丑,哈哈,但是修改成功了):

在这里插入图片描述

参考

word插入超链接
examples
python-docx文档
pypi python-docx

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

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

相关文章

ios包上架系列 二、Xcode打应用市场ipa包

打包的时候一定要断开网络&#xff0c;上线包名只能在打包机配置 检查是否是正式环境&#xff0c;先在模拟器上运行 1、版本名称和本号号记得在这里更改&#xff0c;否则不生效 原因 &#xff1a;info.list <string>$(FLUTTER_BUILD_NAME)</string><key>CFB…

算法:计数类dp

文章目录 一、举个栗子例子1&#xff1a;爬楼梯问题例子2&#xff1a;不同路径例子3&#xff1a;计数子序列 二、基本思路三、典型例题一、ACWing&#xff1a;900. 整数划分1、解法一1.1、状态转移方程1.2、参考代码 O(n) 超时 2、解法二&#xff1a;类似完全背包问题1.1、状态…

【我的小工具】生成React页面类

有了数据表的结构信息&#xff0c;就能生成React 的页面类&#xff0c;快捷方便。 生成界面如下&#xff1a; 生成的React FrmUser.js页面如下&#xff1a; 只需再写里面的操作逻辑代码。

Jupyter Notbook如何安装配置并结合内网穿透实现无公网IP远程连接使用

文章目录 推荐1.前言2.Jupyter Notebook的安装2.1 Jupyter Notebook下载安装2.2 Jupyter Notebook的配置2.3 Cpolar下载安装 3.Cpolar端口设置3.1 Cpolar云端设置3.2.Cpolar本地设置 4.公网访问测试5.结语 推荐 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&am…

通过前缀和来看golang的acm输入输出

前缀和 问题引入 package mainimport ("fmt" )func main() {var n, q, l, r intfmt.Scan(&n, &q)a : make([]int, n)ap : make([]int64, n 1)ap[0] 0for i : 0; i < n; i {fmt.Scan(&a[i])ap[i 1] ap[i] int64(a[i])}for j : 0; j < q; j {f…

Docker端口一直占用问题,docker重置(端口无法释放)(彻底重置docker环境)

文章目录 背景解决方法&#xff1a;彻底重置docker环境1. 停止所有Docker容器2. 删除所有容器3. 删除所有Docker镜像4. 删除所有Docker网络5. 删除所有Docker卷6. 清理Dangling资源7. 停止Docker服务8. 删除Docker数据和配置文件9. 重启Docker服务10. 验证 在这里插入图片描述验…

CSS设置文本

目录 概述&#xff1a; text-aling: text-decoration: text-transform: text-indent: line-height: letter-spacing: word-spacing: text-shadow: vertical-align: white-space: direction: 概述&#xff1a; 在CSS中我们可以设置文本的属性&#xff0c;就像Word文…

CUDA 12.4文档3 内存层次异构变成计算能力

5.3 内存层次 Memory Hierarchy CUDA线程在执行过程中可能会访问多个内存空间的数据&#xff0c;如图6所示。每个线程都有自己的私有本地内存。 每个线程块都有一个对块内所有线程可见的共享内存&#xff0c;并且其生命周期与块相同。线程块集群中的线程块可以对彼此的共享内…

springboot上传模块到私服,再用pom引用下来

有时候要做一个公司的公共服务模块。不能说大家都直接把代码粘贴进去&#xff0c;因为会需要维护很多份&#xff1b;这样就剩下两个方式了。 方式一&#xff1a;自己独立部署一个公共服务的服务&#xff0c;全公司都调用&#xff0c;通过http、rpc或者grpc的方式&#xff0c;这…

【C++杂货铺】模板进阶

目录 &#x1f308;前言&#x1f308; &#x1f4c1; 泛型编程 &#x1f4c1; 函数模板 &#x1f4c2; 概念 &#x1f4c2; 格式 &#x1f4c2; class 和 typename &#x1f4c2; 原理 &#x1f4c2; 函数模板实例化 &#x1f4c2; 匹配原则 &#x1f4c1; 类模板 &#x1…

MySOL之旅--------MySQL数据库基础( 2 )

本篇碎碎念:尽自己最大的努力,直到筋疲力尽为止,加油 今日份励志文案: 别人都在前进,我为什么要停下 目录 补上一条博客缺失的内容 常用数据类型 数值类型&#xff1a; 字符串类型&#xff1a; 日期/时间类型&#xff1a; 二进制类型&#xff1a; 其他类型&#xff1a; …

大话设计模式——24.迭代器模式(Iterator Pattern)

简介 提供一种方法顺序访问一个聚合对象中各个元素&#xff0c;而又不暴露该对象的内部实现。&#xff08;Java中使用最多的设计模式之一&#xff09; UML图 应用场景 Java的集合对象&#xff1a;Collection、List、Map、Set等都有迭代器Java ArrayList的迭代器源码 示例 简…

书生·浦语大模型实战营之LMDeploy 量化部署 LLM-VLM 实践

书生浦语大模型实战营之LMDeploy 量化部署 LLM-VLM 实践 创建开发机 打开InternStudio平台&#xff0c;创建开发机。 填写开发机名称&#xff1b;选择镜像Cuda12.2-conda&#xff1b;选择10% A100*1GPU&#xff1b;点击“立即创建”。注意请不要选择Cuda11.7-conda的镜像&#…

2024年腾讯云优惠活动大全

随着云计算技术的日益成熟&#xff0c;越来越多的企业和个人开始选择将业务和数据迁移到云端。作为国内领先的云服务提供商&#xff0c;腾讯云一直致力于为用户提供高效、稳定、安全的云服务体验。在2024年&#xff0c;腾讯云推出了一系列优惠活动&#xff0c;旨在让更多用户能…

了解Vue路由守卫

一、理解&#xff1a; 路由守卫就是通过URL访问组件的过程中&#xff0c;可以设置回调函数做拦截&#xff0c;判断是否允许该URL访问组件。这个过程出现的回调函数&#xff0c;我们叫做路由守卫钩子函数。 路由守卫有3种 1、全局路由守卫 在./router/index.js 文件中&#xff0…

Web服务器架构设计(学习笔记)

软件架构风格 质量属性与架构评估 Web架构综合考察 什么叫做架构风格&#xff1f;又有哪些架构风格&#xff1f;不同的架构风格的优劣如何? 有哪些层次的负载均衡实现&#xff1f;优劣如何&#xff1f; 有哪些层面的集群切片实现&#xff1f; 什么叫做小前端&#xff0c…

fs.1.10 ON CENTOS7 dockerfile模式

概述 freeswitch是一款简单好用的VOIP开源软交换平台。 centos7 docker上编译安装fs.1.10的流程记录&#xff0c;本文使用dockerfile模式。 环境 docker engine&#xff1a;Version 24.0.6 centos docker&#xff1a;7 freeswitch&#xff1a;v1.10.7 dockerfile 创建空…

茴香豆:搭建你的 RAG 智能助理(笔记)

视频地址&#xff1a;https://www.bilibili.com/video/BV1QA4m1F7t4 文档地址&#xff1a;https://github.com/InternLM/Tutorial/blob/camp2/huixiangdou/readme.md 作业地址&#xff1a;https://github.com/InternLM/Tutorial/blob/camp2/huixiangdou/homework.md 茴香豆项目…

国外客户代采1688商品如何实现自动化对接

要实现国外客户代采1688商品的自动化对接&#xff0c;你可以考虑以下步骤&#xff1a; 选择合适的代采平台&#xff1a;选择一个适合你的需求和预算的代采平台&#xff0c;例如Alibaba.com、Amazon FBA代采等。 注册并创建账户&#xff1a;根据你选择的代采平台&#xff0c;注…

git 删除本地分支 删除远程仓库分支

语法&#xff1a; 删除本地分支 git branch -D <分支名>删除远程分支 git push <remote名称> <分支名> --delete 示例&#xff1a; 删除本地分支 git branch -D feature/test_listview删除远程分支 git push origin feature/test_listview --delete 两个…