美文网首页
python-docx 使用笔记

python-docx 使用笔记

作者: koxxxy | 来源:发表于2020-02-11 21:31 被阅读0次

    python-docx使用文档

    表格篇

    1. 基本操作
    from docx import Document
    from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL, WD_ROW_HEIGHT_RULE
    from docx.shared import Cm, Pt
    
    # 新建表格
    table = Document().add_table(rows, cols, style)
    table.autofit = True  # 自适应宽度 True or False
    table.alignment = WD_TABLE_ALIGNMENT.CENTER  # 表对正类型 LEFT|CENTER|RIGHT
    
    # 新增表格
    row = table.add_row()  # 底部新增行
    column = table.add_column()  # 右侧新增列
    
    # 合并表格
    table.rows[in ].cells[int].merge(table.rows[int].cells[int])
    
    # 插入内容
    table.rows[n].cells[m].text = str  # 第n行往右第m个单元格
    table.columns[n].cells[m].text = str  # 第n列往下第m个单元格
    
    # 单元格垂直中央对齐 Both|Bottom|lCenter|Top
    table.rows[int].cells[int].vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    
    # 单元格水平中央对齐 LEFT|CENTER|RIGHT|JUSTIFY|DISTRIBUTE|JUSTIFY_MED|JUSTIFY_HI|JUSTIFY_LOW|THAI_JUSTIFY
    table.rows[int].cells[int].paragraphs[int].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    
    # 单元格字体样式
    table.rows[int].cells[int].paragraphs[int].runs[int].font.name = '字体名称'
    table.rows[int].cells[int].paragraphs[int].runs[int].font.size=Pt(int) # 字号
    
    
    
    1. 列出所有style
    from docx import Document
    from docx.enum.style import WD_STYLE_TYPE
    
    document = Document(file=path)
    styles = document.styles
    # 生成所有表样式
    for s in styles:
        print(s)
    
    1. 表格内插入图片
    import docx
    pic = "some_picture.jpg"
    document = docx.Document()
    tbl = document.add_table(rows=1, cols=1)
    row_cells = tbl.add_row().cells
    paragraph = row_cells[0].paragraphs[0]
    run = paragraph.add_run()
    run.add_picture(pic, width = 1400000, height = 1400000)
    document.save("demo.docx")
    
    

    文本篇

    from docx import Document
    from docx.enum.text import WD_ALIGN_PARAGRAPH
    
    document = Document(file=path)
    
    # 删除某一段落
    document.paragraphs[int].clear()
    
    # 新增段落
    paragraph = document.add_paragraph()
    # 修改段落对齐 LEFT|CENTER|RIGHT|JUSTIFY|DISTRIBUTE|JUSTIFY_MED|JUSTIFY_HI|JUSTIFY_LOW|THAI_JUSTIFY
    paragraph .alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    

    相关文章

      网友评论

          本文标题:python-docx 使用笔记

          本文链接:https://www.haomeiwen.com/subject/sfjffhtx.html