python-docx 快速入手教程

发布时间 2023-04-19 14:38:06作者: Mlianga

python-docx  

使用文档地址:https://www.osgeo.cn/python-docx/user/documents.html

安装:pip install python-docx

from docx import Document

提取文字

打开文件
doc = Document('filename.docx')
print(doc.paragraphs) #输出段落

    doc.paragraphs :得到一个列表,包含段落实例
    len(doc.paragraphs) :得到段落的个数
    paragraph.text : 得到该段落的文字内容

获取文字块 run
paragraph.runs :得到一个列表,包含每个文字块
run.text :得到该文字块的文字内容

获取整个文本


向文档中写入内容
添加文字
添加标题:
    doc.add_heading('标题名称',level=标题等级):添加标题
    style.name :获取标题名 0是title, 后面是heading

添加段落:
    doc.add_paragraph('段落文字内容',style='')
        style='List Number' :有序列表 123
        style='List Bullet' :无序列表

添加文字块
    paragraph.add_run('文字内容').属性
        属性:bold=True :加粗
             italic=True :斜体

添加图片:
    doc.add_picture('图片地址')
    doc.add_picture('图地址',width='',height='')
    from docx.shared import Cm :尺寸相关

添加表格
    table = doc.add_table(rows='多少行',cols='多少列',表格形式)
    写入数据不得超过设置的行列
    cell = table.rows[0].cells :获取指定行
    cell[col].text = '添加内容'
    (两个for循环插入)

    table.cell(row,col).text :快捷插入
    table = doc.add_table(row=6,cols=6)
    for i in range(0,6):
        for j in range(0,6):
            table.cell(i,j).text = '内容'

添加分行
    runs.add_break()

添加分页
    doc.add_page_break()

调整文档样式 : True False None(默认)
    text文档属性:
    bold:粗体
    italic:斜体
    underline:下划线
    strike:删除线
    double_strike:双删除线
    all_caps:大写首字母
    small_caps:大写首字母,小写字母小两个点
    shadow:阴影
    outline:轮廓线,不是实心
    rtl:从右往左写
    imprint:刻入页面的方式出现
    emboss:凸出页面的方式出现

对文字字体样式修改
run.font.样式 = xxx

修改段落样式 paragraph.paragraph_format.
    对齐样式
    doc.paragraphs.alignment = 对其方式

    可选的对齐方式:
    LEFT,CENTER,RIGHT,JUSTIFY,DISTRIBUTE,JUSTIFY_MED,JUSTIFY_HI,JUSTIFY_LOW,THAI_JUSTIFY

    行间距调整
    paragraph.paragraph_format.line_spacing = 行间距
    注意用浮点数,5.0=5倍行距

    段前与段后间距
    paragraph.paragraph_format.space_before = Pt(12)
    Pr(12) 表示12磅

    缩进
    左缩进:paragraph.paragraph_format.left_indent = Inches(0.5)
    右缩进:paragraph.paragraph_format.right_indent
    首行缩进:....first_line_indent

    制表位
    tab_stops = paragraph.format.tab_stops
    tab_stop = tab_stops.add_tab_stop(Inches(1))
    tab_stop.positin 位置
    tab_stop.posit.inches 大小

字符样式修改
    font = run.font.属性
    属性:
    size:字体大小
    underline:下划线
    color.rgb:颜色

 

 

docx.shared 单位
    Enches,Pt,Cm,Length,RGBColor