使用DocxTemplate绘制带边框的表格
{"title": "使用DocxTemplate绘制带边框的表格", "description": "本文介绍如何使用DocxTemplate库绘制带有边框的表格。文章提供了完整的代码示例,并详细解释了代码的每个部分,包括创建表格、设置样式、添加数据等步骤。", "keywords": "DocxTemplate, 表格, 边框, python, 文档生成, 自动化", "content": "使用DocxTemplate可以绘制一个带有边框的表格,具体代码如下所示:\n\npython\nfrom docxtpl import DocxTemplate\nfrom docx.shared import Pt\n\n# 创建DocxTemplate对象\ndoc = DocxTemplate("template.docx")\n\n# 定义表格数据\ndata = [\n {"name": "张三", "age": "20", "gender": "男"},\n {"name": "李四", "age": "25", "gender": "女"},\n {"name": "王五", "age": "30", "gender": "男"},\n]\n\n# 添加表格到文档中\ntable = doc.add_table(rows=1, cols=3)\ntable.autofit = False # 关闭自动调整列宽\ntable.allow_autofit = False # 关闭自动调整列宽\n\n# 设置表格样式\nfor row in table.rows:\n for cell in row.cells:\n cell.width = Pt(100) # 设置列宽\n cell.vertical_alignment = "center" # 垂直居中\n cell.paragraphs[0].paragraph_format.alignment = 1 # 水平居中\n cell.paragraphs[0].paragraph_format.space_after = Pt(0) # 段后间距\n cell.paragraphs[0].paragraph_format.space_before = Pt(0) # 段前间距\n cell.paragraphs[0].paragraph_format.line_spacing = 1.5 # 行间距\n\n# 设置表头\nheader_cells = table.rows[0].cells\nheader_cells[0].text = "姓名"\nheader_cells[1].text = "年龄"\nheader_cells[2].text = "性别"\n\n# 设置表格内容\nfor item in data:\n row_cells = table.add_row().cells\n row_cells[0].text = item["name"]\n row_cells[1].text = item["age"]\n row_cells[2].text = item["gender"]\n\n# 保存文档\ndoc.save("output.docx")\n\n\n在上述代码中,首先创建了一个DocxTemplate对象,然后定义了一个包含表格数据的列表。然后通过doc.add_table()方法添加一个表格到文档中,设置了表格的样式,包括列宽、垂直居中、水平居中等。接着设置表头和表格内容,最后保存文档。运行代码后,将生成一个带有边框的表格的文档。
原文地址: https://www.cveoy.top/t/topic/pVo3 著作权归作者所有。请勿转载和采集!