python-docx常用操作

本文记录了在使用python-docx时常用到的一些函数和方法。

导入库

本文章中的代码会用到的库

import docx
from docx import Document
from docx.shared import RGBColor, Cm
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT, WD_TABLE_ALIGNMENT
from docx.enum.style import WD_STYLE_TYPE
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml

创建文档

创建一个以当前目录下的test.docx为模板的文档。

document = Document('./test.docx')

保存文档

将文档保存在’./savePath.docx’路径

document.save('./savePath.docx')

表格操作

获取文档中的第1个表格,以此类推可获得文档中的第n张图片和段落等等。

table = document.tables[0]

添加表格

table = document.add_table(2, 3) # 创建一个2行3列的表格

表格添加行

table.add_row() # 在末尾添加加1行

获取表格行数和列数

row = len(table.rows)
column = len(table.columns)

给表格单元格赋值

table.cell(0, 0).text = '单元格的值'

设置表格单元格宽度

table.cell(n, m).width = Cm(3) # 设置第n-1行、m-1列单元格宽度为3cm

设置单元格内容居中对齐

table.cell(n, m).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

设置表格首行颜色

tableBgColor(table, column, RGBColor(255, 255, 224))

def tableBgColor(table,column,colorStr):
    shading_list = locals()
    for i in range(column):
        shading_list['shading_elm_'+str(i)] = parse_xml(r'<w:shd {} w:fill="{bgColor}"/>'.format(nsdecls('w'),bgColor = colorStr))
        table.rows[0].cells[i]._tc.get_or_add_tcPr().append(shading_list['shading_elm_'+str(i)])

字体设置

设置字体颜色

paragraphp = table.cell(0, 0).paragraphs[0] # 在单元格中添加段落
run = paragraphp.add_run('Pass') # 在段落中添加'Pass'字块
run.font.color.rgb = RGBColor(0, 255, 0) # 设置'Pass'字块颜色为绿色

添加图片

在文档中添加图片,并设置图片高度为8cm

document.add_picture(r'C:\Users\Desktop\测试图片.png', height = Cm(8))

添加标题

添加一级标题

document.add_heading('1级标题',level= 1)

添加二级标题

document.add_heading('2级标题',level= 2)

添加段落

document.add_paragraph() # 可实现换行
paragraph = document.add_paragraph('添加段落')
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 设置段落居中

添加分页符

document.add_page_break()

设置表格行间距

有时候设置完表格单元格的宽和高后,发现不是预期的效果,就要看看是不是段落行间距的设置有问题。

def setTableParagraphsSpace(table, space):
    row = len(table.rows)
    crols = len(table.columns)
    for n in range(0, row):
        for m in range(0, crols):
            table.cell(n, m).paragraphs[0].paragraph_format.space_before = Cm(space)
            table.cell(n, m).paragraphs[0].paragraph_format.space_after = Cm(space)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值