• 【Python自动化】Python-docx基础入门--插入table表格样式设置


    原文作者:我辈李想
    版权声明:文章原创,转载时请务必加上原文超链接、作者信息和本声明。



    前言

    本博客主要介绍插入表格的相关设置,包括字体设置,居中设置,插入图片等。


    一、python-docx安装

    pip install python-docx
    
    • 1

    二、常见用法

    1.设置样式

    document = Document()
    
    #设置word文档中的字体格式
    document.styles['Normal'].font.name = u'宋体'
    document.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.插入标题和段落

    # 段落标题
    document.add_heading('Heading, level 1', level=1)
    paragraph1 = document.add_paragraph("附表 文件列表及相关属性信息") # 行中插入景号
    paragraph1.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT  #居左
    
    • 1
    • 2
    • 3
    • 4

    3.插入图片

    document.add_picture('monty-truth.png', width=Inches(1.25)
    
    • 1

    4.插入表格

    records = (
        (3, '101', 'Spam'),
        (7, '422', 'Eggs'),
        (4, '631', 'Spam, spam, eggs, and spam')
    )
    
    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Qty'
    hdr_cells[1].text = 'Id'
    hdr_cells[2].text = 'Desc'
    for qty, id, desc in records:
        row_cells = table.add_row().cells
        row_cells[0].text = str(qty)
        row_cells[1].text = id
        row_cells[2].text = desc
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    5.纵向改横向

    最近需要docx页面输出,需要将正常纵向页面转为横向页面,查了一些资料,发现很多都是科普的解释,并没有讲出具体怎么做,现在贴出我实现的代码。

    需要引入的:

    from docx import Document
    from docx.enum.section import WD_ORIENT
    纵向转横向的代码:
    
    document = Document()
    section = document.sections[0]
    new_width, new_height = section.page_height, section.page_width
    section.orientation = WD_ORIENT.LANDSCAPE
    section.page_width = new_width
    section.page_height = new_height
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    三、创建表格

    1.表格居中显示

    from docx import Document
    from docx.enum.table import WD_TABLE_ALIGNMENT
    
    document = Document()
    table = document.add_table(rows=2, cols=2)
    # 对表格进行对齐
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    
    document.save('my_table.docx')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2.设置表格列宽

    要设置表格的列宽,可以使用 Table 对象的 columns 属性。该属性返回一个列宽列表,可以按索引对其进行更改以设置不同列的宽度。以下是一个示例:
    方式一

    from docx import Document
    
    document = Document()
    table = document.add_table(rows=2, cols=3)
    
    # 设置第一列宽度为1英寸
    table.columns[0].width = 914400
    # 设置第二列宽度为2英寸
    table.columns[1].width = 1828800
    # 设置第三列宽度为3英寸
    table.columns[2].width = 2743200
    document.save('my_table.docx')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    方式二

    c_list = ['序号','名字',"景号","成像时间","缩略图"]
    # 设置列宽
    for index,column_name in enumerate(c_list):
        table.columns[index].vertical_alignment = WD_ALIGN_PARAGRAPH.CENTER
        if column_name == "景号":
            table.columns[index].width  = Inches(3.3)
        elif column_name == "成像时间":
            table.columns[index].width  = Inches(0.8)
        elif column_name == "缩略图":
            table.columns[index].width  = Inches(1.1)
        elif column_name == "是否满足合同要求":
            table.columns[index].width  = Inches(0.8)
        else:
            table.columns[index].width  = Inches(0.5)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这个示例中,我们首先创建了一个包含 2 行和 3 列的表格。然后,我们按索引对列宽列表进行更改,以便将第一列设置为 1 英寸宽、第二列设置为 2 英寸宽,第三列设置为 3 英寸宽。最后,我们将文档保存到文件 ‘my_table.docx’ 中。

    3.固定列宽

    要固定表格的列宽,你可以使用Table.auto_fit方法,并将autofit参数设置为False。然后,可以使用Table.columns属性来访问表格中的列,并设置每个列的宽度。这里有个例子:

    from docx import Document
    from docx.shared import Inches
    
    document = Document()
    table = document.add_table(rows=2, cols=3, style='Table Grid')
    
    # Turn off autofit  固定列宽
    table.autofit = False
    
    # Set column widths
    table.columns[0].width = Inches(2.0)
    table.columns[1].width = Inches(3.0)
    table.columns[2].width = Inches(4.0)
    
    # Add cell content
    row = table.rows[0]
    row.cells[0].text = 'Column 1'
    row.cells[1].text = 'Column 2'
    row.cells[2].text = 'Column 3'
    
    document.save('my_table.docx')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在这个例子中,我们首先创建一个2行3列的表格,并将autofit参数设置为False。接着,我们设置每个列的宽度,分别为2、3和4英寸。最后,我们在第一行的每个单元格中添加文本。

    注意,在使用Table.columns属性时,索引从0开始。因此,我们使用table.columns[0]来访问第一列,使用table.columns[1]来访问第二列,以此类推。

    4.设置表格内容样式(字体)

    方式一

    # 创建表格
    table = document.add_table(rows=1, cols=len(c_list),style ='Table Grid')
    #设置整个表格字体属性
    table.style.font.bold = True
    table.style.font.name=u'宋体'
    table.style.font.size= Pt(10)
    table.style.font.color.rgb= RGBColor(0, 0, 0)
    table.style.paragraph_format.alignment=WD_PARAGRAPH_ALIGNMENT.CENTER 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    方式二

    from docx import Document
    from docx.enum.style import WD_STYLE_TYPE
    
    # 创建一个新文档对象
    document = Document()
    
    # 定义样式
    table_style_name = 'mystyle'
    table_style= document.styles.add_style(table_style_name, WD_STYLE_TYPE.TABLE)
    table_style.font.bold = True
    table_style.font.name=u'宋体'
    table_style.font.size= Pt(10)
    table_style.font.color.rgb= RGBColor(0, 0, 0)
    table_style.paragraph_format.alignment=WD_PARAGRAPH_ALIGNMENT.CENTER 
    
    # 创建一个带有三列和四行的表格
    # table = document.add_table(rows=4, cols=3,style='mystyle')
    table = document.add_table(rows=4, cols=3)
    
    # 设置表格样式
    table.style = table_style
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    5.首行样式(水平居中和垂直居中)

    # 首行
    hdr_cells = table.rows[0].cells
    for i,hdr in enumerate(hdr_cells):
        hdr.text = c_list[i]
        # 设置单元格填充颜色为浅灰色
    	hdr.fill.solid()
    	hdr.fill.fore_color.rgb = (220, 220, 220)
    	# 设置单元格文本格式为粗体
    	hdr.paragraphs[0].runs[0].bold = True
    	# 垂直居中+水平居中
    	hdr.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
    	hdr.vertical_alignment = WD_ALIGN_PARAGRAPH.CENTER
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    6.单元格中插入图片

    要在表格中插入图片,你可以使用add_picture方法插入图片,并指定插入到哪个单元格中。这里有个例子:

    from docx import Document
    from docx.shared import Inches
    
    document = Document()
    table = document.add_table(rows=2, cols=2)
    
    # Add image to cell (0, 1)
    cell = table.cell(0, 1)
    img_path = 'picture.png'
    paragraph = cell.paragraphs[0]
    run = paragraph.add_run()
    run.add_picture(img_path, width=Inches(2.0))
    
    document.save('my_table.docx')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这个例子中,我们首先创建一个2行2列的表格,在第1行第2列插入一张名为“picture.png”的图片。我们首先获取该单元格的段落,然后在段落中添加一个run对象,然后调用add_picture方法将图片插入到run对象中。

    注意,我们在调用add_picture方法时使用了width=Inches(2.0),以确保图片的宽度为2英寸。你可以根据需要调整宽度。

  • 相关阅读:
    力扣刷题第二十三天--栈与队列
    MySQL数据类型的选择(详解版)
    你一定用过htop,但你有看懂每个栏位么?
    UE5 CommonUI的使用(附源码版)
    初步利用Ansible实现批量服务器自动化管理
    基于VDI2230规范的螺栓评估(上)
    Pro_07丨波动率因子3.0与斜率因子
    有效的字母异位词(C++解法)
    OpenMP 教程(一) 深入剖析 OpenMP reduction 子句
    [数据库]知识点备忘录
  • 原文地址:https://blog.csdn.net/qq_15028721/article/details/133683476