Word自动化办公 python-docx
创始人
2025-05-28 09:57:33
0

Word自动化办公 python-docx

目录

文章目录

      • **Word自动化办公 python-docx**
      • **1.字体大小参照**
      • **2.python-docx 模块**
      • **3.读取和保存word**
      • **4.查询段落**
      • **5.增减段落**
        • **5.1.文档末尾添加段落**
        • **5.2.添加带有样式的段落**
        • **5.3.修改已有段落样式:**
        • **5.4.在某一段落前添加段落**
        • **5.5.删除某一段**
        • **项目综合应用**
      • **6.段落对齐**
        • **1.需要导入段落对齐模块。**
        • **2.设置段落居中对齐**
        • **3.对齐方式常用的有:**
      • **7.缩进**
        • **7.1.导入长度模块。**
        • **7.2.设置左缩进**
        • **7.3.设置右缩进**
        • **7.4.设置首行缩进**
      • **8.段前/段后间距**
        • **8.1.段前间距**
        • **8.2.段后间距**
      • **9.行距**
        • **9.11.设置固定值行间距**
        • **9.2.设置特殊行间距**
      • **10.编辑表格**
          • 10.1 添加表格
          • 1.2 添加行列
          • 1.3 表格样式
      • **11.编辑图片**

1.字体大小参照

字体大小参照
字号‘八号’对应磅值5
字号‘七号’对应磅值5.5
字号‘小六’对应磅值6.5
字号‘六号’对应磅值7.5
字号‘小五’对应磅值9
字号‘五号’对应磅值10.5
字号‘小四’对应磅值12
字号‘四号’对应磅值14
字号‘小三’对应磅值15
字号‘三号’对应磅值16
字号‘小二’对应磅值18
字号‘二号’对应磅值22
字号‘小一’对应磅值24
字号‘一号’对应磅值26
字号‘小初’对应磅值36
字号‘初号’对应磅值42

2.python-docx 模块

pip  install python-docx -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

增减段落、对齐、缩进、段前/段后间距、行距

3.读取和保存word

from docx import Documentdocument = Document(f"{Templates}/FM1项目氨基酸序列.docx")new_doc_name = f"{Product}/FM1项目氨基酸序列{PN}.docx"
document.save(new_doc_name)

4.查询段落

print(len(document.paragraphs)) print(document.paragraphs[1].text)

5.增减段落

5.1.文档末尾添加段落

document.add_paragraph("在文末添加段落")

5.2.添加带有样式的段落

document.add_paragraph("在文末添加段落",style="Heading 1")

5.3.修改已有段落样式:

doc.paragraphs[0].style = "Heading 1"
段落样式比较多,大概有36种。经常用到的有:Normal—正文,Heading 1-9—标题1-9,Title—标题。在word中,可以通过Ctrl+Alt+Shift+s来查看所有样式。

5.4.在某一段落前添加段落

p = doc.paragraphs[0]
p.insert_paragraph_before("这一段在第一段落前。")

tips:没有在某一段落后添加段落!

5.5.删除某一段

doc.paragraphs[0].clear()

项目综合应用

    document.paragraphs[55] = document.paragraphs[55].clear()for i in range(num_li[7].shape[0]):run = document.paragraphs[55].add_run(f"{(num_li[7][0][i])}")run.font.name = u"Times New Roman"run.font.size = Pt(10.5)run.font.italic = True  # 设置字体斜体run.bold = True  # 字体是否加粗run.font.underline = True  # 设置下划线样式document.paragraphs[55].add_run(f"\n")

6.段落对齐

1.需要导入段落对齐模块。

from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

2.设置段落居中对齐

doc.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

3.对齐方式常用的有:

LEFT—左对齐CENTER—居中对齐RIGHT—右对齐JUSTIFY—两端对齐只需要修改,WD_PARAGRAPH_ALIGNMENT.,后面的内容即可。

7.缩进

7.1.导入长度模块。

from docx.shared import Inches,Pt,Cm

Inches—英寸,Pt—磅,Cm—厘米。

这三个是常用单位,可以根据自己的需要导入一个及多个。

7.2.设置左缩进

p = doc.paragraphs[0]
p.paragraph_format.left_indent = Inches(0.2)  #第1段左缩进0.2英寸

7.3.设置右缩进

p = doc.paragraphs[0]
p.paragraph_format.right_indent = Inches(0.2)

7.4.设置首行缩进

p = doc.paragraphs[0]
p.paragraph_format.first_line_indent = Inches(0.3)

8.段前/段后间距

8.1.段前间距

p = doc.paragraphs[0]
p.paragraph_format.space_before = Pt(18)  #第一段段前间距为18磅

8.2.段后间距

p = doc.paragraphs[0]
p.paragraph_format.space_after = Pt(18)

9.行距

9.11.设置固定值行间距

p = doc.paragraphs[0]
p.paragraph_format.line_spacing = Pt(20)  #行间距为20磅

9.2.设置特殊行间距

导入模块:

from docx.enum.text import WD_LINE_SPACING

设置行间距:

p = doc.paragraphs[0]
p.paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE
常用的特殊行间距有:ONE_POINT_FIVE—1.5倍行距AT_LEAST—最小值DOUBLE—2倍行距SINGLE—单倍行距

10.编辑表格

    document = Document("xxx.docx")table = document.tables# print(len(table))df1 = num_li[0].copy()for j in range(1, 4):  # 行for i in range(4):  # 列table[0].cell(j, 1 + i).paragraphs[0].clear()run = table[0].cell(j, 1 + i).paragraphs[0].add_run(f'{df1[i][j - 1]}')table[0].cell(j, 1 + i).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTERrun.font.name = u"Times New Roman"run.font.size = Pt(12)
10.1 添加表格

添加表格很简单,只需要调用一下add_table()即可,返回一个Table对象,参数可以指定行、列、样式

from docx import Documentdoc = Document()
# 添加一个5行3列的表格,样式是网格实线
table = doc.add_table(5, 3, style="Table Grid")
doc.save('./test.docx')
1.2 添加行列
from docx import Document
from docx.shared import Cm, RGBColor, Pt
...
table.add_row()  # 在最下面添加一行
table.add_column(Pt(25))  # 在最右边添加一列并指定宽度为25磅
1.3 表格样式
table.cell(1, 2).text = "xiongsheng"
table.style.font.size = Pt(15)  # 字体大小15磅
table.style.font.color.rgb = RGBColor.from_string("6495ED")  # 字体颜色
table.style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT  # 左对齐

11.编辑图片

    document = Document("xxx.docx")# for i in range(161):#     print(document.paragraphs[i].text)# 获取服务器的图片import requestsfrom PIL import Imagefrom io import BytesIO# 保存服务器的图片到本地for img_i in range(2):img_src = num_li[13][1][img_i]response = requests.get(img_src)image = Image.open(BytesIO(response.content))image.save(f'{Picture}/{img_i + 1}.png')# 查看文档中图片个数# pic_num = len(document.inline_shapes)# print(pic_num)# print(document.paragraphs[144].text)# print(document.paragraphs[146].text)for para_i in [144, 146]:# 实现思路,先看看图片在第几行,找到图片的位置,先删除在添加图片document.paragraphs[para_i] = document.paragraphs[para_i].clear()para = document.paragraphs[para_i]san = 1if para_i == 146:san = 2new_img_path = f"{Picture}/{san}.png"para.add_run().add_picture(new_img_path, width=Cm(11.00), height=Cm(7.34))new_doc_name = "xxx.docx"document.save(new_doc_name)

相关内容

热门资讯

AWSECS:访问外部网络时出... 如果您在AWS ECS中部署了应用程序,并且该应用程序需要访问外部网络,但是无法正常访问,可能是因为...
AWSElasticBeans... 在Dockerfile中手动配置nginx反向代理。例如,在Dockerfile中添加以下代码:FR...
银河麒麟V10SP1高级服务器... 银河麒麟高级服务器操作系统简介: 银河麒麟高级服务器操作系统V10是针对企业级关键业务...
北信源内网安全管理卸载 北信源内网安全管理是一款网络安全管理软件,主要用于保护内网安全。在日常使用过程中,卸载该软件是一种常...
AWR报告解读 WORKLOAD REPOSITORY PDB report (PDB snapshots) AW...
AWS管理控制台菜单和权限 要在AWS管理控制台中创建菜单和权限,您可以使用AWS Identity and Access Ma...
​ToDesk 远程工具安装及... 目录 前言 ToDesk 优势 ToDesk 下载安装 ToDesk 功能展示 文件传输 设备链接 ...
群晖外网访问终极解决方法:IP... 写在前面的话 受够了群晖的quickconnet的小水管了,急需一个新的解决方法&#x...
不能访问光猫的的管理页面 光猫是现代家庭宽带网络的重要组成部分,它可以提供高速稳定的网络连接。但是,有时候我们会遇到不能访问光...
Azure构建流程(Power... 这可能是由于配置错误导致的问题。请检查构建流程任务中的“发布构建制品”步骤,确保正确配置了“Arti...