Word自动化办公 python-docx

  • Post author:
  • Post category:python

Word自动化办公 python-docx

目录

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 Document

document = 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.CENTER
            run.font.name = u"Times New Roman"
            run.font.size = Pt(12)
10.1 添加表格

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

from docx import Document

doc = 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 requests
    from PIL import Image
    from 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 = 1
        if para_i == 146:
            san = 2
        new_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)


版权声明:本文为weixin_45523107原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。