使用DocxTemplate可以绘制一个带有边框的表格,具体代码如下所示:

from docxtpl import DocxTemplate
from docx.shared import Pt

# 创建DocxTemplate对象
doc = DocxTemplate("template.docx")

# 定义表格数据
data = [
    {"name": "张三", "age": "20", "gender": "男"},
    {"name": "李四", "age": "25", "gender": "女"},
    {"name": "王五", "age": "30", "gender": "男"},
]

# 添加表格到文档中
table = doc.add_table(rows=1, cols=3)
table.autofit = False  # 关闭自动调整列宽
table.allow_autofit = False  # 关闭自动调整列宽

# 设置表格样式
for row in table.rows:
    for cell in row.cells:
        cell.width = Pt(100)  # 设置列宽
        cell.vertical_alignment = "center"  # 垂直居中
        cell.paragraphs[0].paragraph_format.alignment = 1  # 水平居中
        cell.paragraphs[0].paragraph_format.space_after = Pt(0)  # 段后间距
        cell.paragraphs[0].paragraph_format.space_before = Pt(0)  # 段前间距
        cell.paragraphs[0].paragraph_format.line_spacing = 1.5  # 行间距

# 设置表头
header_cells = table.rows[0].cells
header_cells[0].text = "姓名"
header_cells[1].text = "年龄"
header_cells[2].text = "性别"

# 设置表格内容
for item in data:
    row_cells = table.add_row().cells
    row_cells[0].text = item["name"]
    row_cells[1].text = item["age"]
    row_cells[2].text = item["gender"]

# 保存文档
doc.save("output.docx")

在上述代码中,首先创建了一个DocxTemplate对象,然后定义了一个包含表格数据的列表。然后通过doc.add_table()方法添加一个表格到文档中,设置了表格的样式,包括列宽、垂直居中、水平居中等。接着设置表头和表格内容,最后保存文档。运行代码后,将生成一个带有边框的表格的文档

请使用DocxTemplate 绘制一个表格要求有边框

原文地址: https://www.cveoy.top/t/topic/icIW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录