使用Python在Word文档中创建表格并设置各种格式
在现代办公环境中,Word 文档是信息传递和报告输出的重要载体。从制作财务报表、项目进度表,到创建产品对比清单、员工信息表,表格以其清晰的结构化展示能力,成为各类文档中不可或缺的元素。然而,当需要处理大量数据或定期生成标准化报告时,手动在 Word 中创建和格式化表格不仅耗时耗力,还容易出现格式不一致、数据录入错误等问题。而 Python 凭借其强大的自动化处理能力,结合专业的文档操作库,可以高效地实现 Word 表格的批量创建、格式化和数据填充,大幅提升工作效率。
本文将使用 Free Spire.Doc for Python 展示如何在 Word 文档中创建基础表格、设置表格样式、合并与拆分单元格、创建嵌套表格等实用功能,结合实际业务场景的数据示例,帮助你快速掌握 Word 表格自动化处理技能。
1. 环境准备与库安装
首先需要安装 Free Spire.Doc for Python:
pip install spire.doc.free
安装完成后,我们可以开始创建 Word 文档并准备表格。下面是一个创建 Word 文件的简单示例:
from spire.doc import *
from spire.doc.common import *
# 创建一个新的 Word 文档
document = Document()
# 添加一个节
section = document.AddSection()
# 添加一个段落作为标题
title = section.AddParagraph()
text_range = title.AppendText("员工信息表")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
text_range.CharacterFormat.Bold = True
text_range.CharacterFormat.FontSize = 18
# 保存初始文件
document.SaveToFile("EmployeeTable.docx", FileFormat.Docx)
document.Close()
print("Word 文档已创建:EmployeeTable.docx")说明:Document 对象代表整个 Word 文档,AddSection() 方法添加一个新的节,AddParagraph() 方法添加段落。这里我们创建了一个包含标题的文档,为后续创建表格做好准备。
2. 创建基础表格:员工信息管理
假设我们需要为人力资源部门创建一份员工信息表,包含姓名、部门、职位、入职日期和联系方式等字段。我们可以在代码中直接生成表格并填充数据:
from spire.doc import *
from spire.doc.common import *
# 创建文档
document = Document()
section = document.AddSection()
# 添加标题
title = section.AddParagraph()
text_range = title.AppendText("员工信息表")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
text_range.CharacterFormat.Bold = True
text_range.CharacterFormat.FontSize = 18
section.AddParagraph() # 添加空行
# 准备表头和数据
headers = ["姓名", "部门", "职位", "入职日期", "联系方式"]
employees = [
["张三", "技术部", "软件工程师", "2020-03-15", "13800138001"],
["李四", "市场部", "市场经理", "2019-06-20", "13800138002"],
["王五", "人力资源部", "人力资源专员", "2021-01-10", "13800138003"],
["赵六", "财务部", "会计", "2018-11-05", "13800138004"],
["钱七", "技术部", "产品经理", "2020-08-22", "13800138005"],
]
# 创建表格
table = section.AddTable(True)
table.ResetCells(len(employees) + 1, len(headers))
# 设置表头行
header_row = table.Rows[0]
header_row.IsHeader = True
header_row.Height = 30
header_row.HeightType = TableRowHeightType.Exactly
# 填充表头并设置样式
for i, header in enumerate(headers):
cell = header_row.Cells[i]
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
cell.CellFormat.Shading.BackgroundPatternColor = Color.get_Gray()
paragraph = cell.AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
text_range = paragraph.AppendText(header)
text_range.CharacterFormat.Bold = True
text_range.CharacterFormat.FontSize = 12
# 填充数据行
for row_idx, employee in enumerate(employees):
data_row = table.Rows[row_idx + 1]
data_row.Height = 25
data_row.HeightType = TableRowHeightType.Exactly
for col_idx, value in enumerate(employee):
cell = data_row.Cells[col_idx]
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
cell.CellFormat.Shading.BackgroundPatternColor = Color.Empty()
paragraph = cell.AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
paragraph.AppendText(value)
# 设置隔行变色
for row_idx in range(1, table.Rows.Count):
if row_idx % 2 == 0:
row = table.Rows[row_idx]
for cell_idx in range(row.Cells.Count):
cell = row.Cells[cell_idx]
cell.CellFormat.Shading.BackgroundPatternColor = Color.get_LightBlue()
# 保存文档
document.SaveToFile("EmployeeTable.docx", FileFormat.Docx)
document.Close()
print("员工信息表已创建完成")文档预览:

说明:
通过 section.AddTable(True) 创建表格,ResetCells() 方法设置表格的行数和列数。我们为表头行设置了灰色背景和粗体字,数据行居中对齐,并实现了隔行变色效果,使表格更加清晰易读。
3. 设置表格样式与边框
为了让表格更具专业性和可读性,我们可以应用预设的表格样式并自定义边框样式:
from spire.doc import *
from spire.doc.common import *
# 创建文档
document = Document()
section = document.AddSection()
# 添加标题
title = section.AddParagraph()
text_Range = title.AppendText("季度销售报表")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
text_Range.CharacterFormat.Bold = True
text_Range.CharacterFormat.FontSize = 18
section.AddParagraph()
# 创建表格
table = section.AddTable(True)
table.ResetCells(5, 4)
# 填充表头
headers = ["产品名称", "第一季度", "第二季度", "第三季度"]
for i, header in enumerate(headers):
cell = table.Rows[0].Cells[i]
cell.AddParagraph().AppendText(header)
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
# 填充数据
data = [
["笔记本电脑", "120万", "135万", "150万"],
["平板电脑", "85万", "92万", "105万"],
["智能手机", "200万", "220万", "245万"],
["智能手表", "45万", "52万", "60万"],
]
for row_idx, row_data in enumerate(data):
for col_idx, value in enumerate(row_data):
table.Rows[row_idx + 1].Cells[col_idx].AddParagraph().AppendText(value)
# 应用表格样式
table.ApplyStyle(DefaultTableStyle.ColorfulListAccent1)
# 自定义边框样式
table.Format.Borders.BorderType = BorderStyle.Single
table.Format.Borders.LineWidth = 1.0
table.Format.Borders.Color = Color.get_Black()
# 设置外边框加粗
table.Format.Borders.Left.LineWidth = 2.0
table.Format.Borders.Right.LineWidth = 2.0
table.Format.Borders.Top.LineWidth = 2.0
table.Format.Borders.Bottom.LineWidth = 2.0
# 保存文档
document.SaveToFile("SalesReport.docx", FileFormat.Docx)
document.Close()
print("销售报表已创建完成")文档预览:

说明:ApplyStyle() 方法应用预设的表格样式,Format.Borders 属性用于设置边框样式。我们可以单独设置上下左右边框的宽度、颜色和类型,创建专业的表格外观。
4. 合并与拆分单元格:创建复杂表格结构
在实际业务中,我们经常需要创建包含合并单元格的复杂表格结构,例如产品规格对比表:
from spire.doc import *
from spire.doc.common import *
# 创建文档
document = Document()
section = document.AddSection()
# 添加标题
title = section.AddParagraph()
text_range = title.AppendText("产品规格对比表")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
text_range.CharacterFormat.Bold = True
text_range.CharacterFormat.FontSize = 18
section.AddParagraph()
# 创建表格(8行6列)
table = section.AddTable(True)
table.ResetCells(8, 6)
# 填充表头(合并第一行的前3列和后3列)
table.ApplyHorizontalMerge(0, 0, 2) # 合并第1行的第1-3列
table.ApplyHorizontalMerge(0, 3, 5) # 合并第1行的第4-6列
table.Rows[0].Cells[0].AddParagraph().AppendText("基础信息")
table.Rows[0].Cells[3].AddParagraph().AppendText("技术参数")
# 填充第二列表头
sub_headers = ["产品名称", "型号", "价格", "处理器", "内存", "存储"]
for i, header in enumerate(sub_headers):
table.Rows[1].Cells[i].AddParagraph().AppendText(header)
# 填充产品数据
products = [
["ProBook X1", "PB-2024", "5999元", "i7-1360P", "16GB", "512GB SSD"],
["UltraBook Pro", "UB-2024", "7999元", "i7-1370P", "32GB", "1TB SSD"],
["Gaming Laptop", "GL-2024", "9999元", "i9-13900HX", "32GB", "1TB SSD"],
]
for row_idx, product in enumerate(products):
for col_idx, value in enumerate(product):
table.Rows[row_idx + 2].Cells[col_idx].AddParagraph().AppendText(value)
# 合并底部的备注行(合并所有列)
note_row = table.Rows[6]
table.ApplyHorizontalMerge(6, 0, 5)
note_row.Cells[0].AddParagraph().AppendText("注:以上价格仅供参考,实际价格以官网为准。")
# 在最后一行拆分单元格
table.Rows[7].Cells[0].SplitCell(3, 2) # 将第8行第1列拆分为3行2列
# 保存文档
document.SaveToFile("ProductComparison.docx", FileFormat.Docx)
document.Close()
print("产品规格对比表已创建完成")文档预览:

说明:ApplyHorizontalMerge() 方法用于水平合并单元格(同一行内),ApplyVerticalMerge() 方法用于垂直合并单元格(同一列内)。SplitCell() 方法可以将一个单元格拆分为多个单元格,实现更灵活的表格布局。
5. 创建嵌套表格:展示层级数据
嵌套表格可以在一个单元格内包含另一个表格,适用于展示具有层级关系的数据,例如产品目录:
from spire.doc import *
from spire.doc.common import *
# 创建文档
document = Document()
section = document.AddSection()
# 添加标题
title = section.AddParagraph()
text_range = title.AppendText("产品目录")
title.Format.HorizontalAlignment = HorizontalAlignment.Center
text_range.CharacterFormat.Bold = True
text_range.CharacterFormat.FontSize = 18
section.AddParagraph()
# 创建主表格(3行2列)
main_table = section.AddTable(True)
main_table.ResetCells(3, 2)
# 设置主表格列宽
main_table.Rows[0].Cells[0].SetCellWidth(150, CellWidthType.Point)
main_table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
# 填充主表格第一列(产品类别)
main_table.Rows[0].Cells[0].AddParagraph().AppendText("电子产品")
main_table.Rows[1].Cells[0].AddParagraph().AppendText("家居用品")
main_table.Rows[2].Cells[0].AddParagraph().AppendText("办公用品")
# 在第一行第二列创建嵌套表格(电子产品)
nested_table1 = main_table.Rows[0].Cells[1].AddTable(True)
nested_table1.ResetCells(4, 3)
nested_table1.AutoFit(AutoFitBehaviorType.AutoFitToContents)
# 填充嵌套表格1的表头
nested_headers = ["产品名称", "型号", "价格"]
for i, header in enumerate(nested_headers):
cell = nested_table1.Rows[0].Cells[i]
cell.CellFormat.Shading.BackgroundPatternColor = Color.get_LightGray()
cell.AddParagraph().AppendText(header)
# 填充嵌套表格1的数据
electronics = [
["智能手机", "SP-2024", "3999元"],
["平板电脑", "TB-2024", "2999元"],
["智能手表", "SW-2024", "1999元"],
]
for row_idx, item in enumerate(electronics):
for col_idx, value in enumerate(item):
nested_table1.Rows[row_idx + 1].Cells[col_idx].AddParagraph().AppendText(value)
# 在第二行第二列创建嵌套表格(家居用品)
nested_table2 = main_table.Rows[1].Cells[1].AddTable(True)
nested_table2.ResetCells(3, 3)
nested_table2.AutoFit(AutoFitBehaviorType.AutoFitToContents)
for i, header in enumerate(nested_headers):
cell = nested_table2.Rows[0].Cells[i]
cell.CellFormat.Shading.BackgroundPatternColor = Color.get_LightGray()
cell.AddParagraph().AppendText(header)
home_goods = [
["电饭煲", "RC-2024", "599元"],
["空气净化器", "AP-2024", "1299元"],
]
for row_idx, item in enumerate(home_goods):
for col_idx, value in enumerate(item):
nested_table2.Rows[row_idx + 1].Cells[col_idx].AddParagraph().AppendText(value)
# 在第三行第二列创建嵌套表格(办公用品)
nested_table3 = main_table.Rows[2].Cells[1].AddTable(True)
nested_table3.ResetCells(3, 3)
nested_table3.AutoFit(AutoFitBehaviorType.AutoFitToContents)
for i, header in enumerate(nested_headers):
cell = nested_table3.Rows[0].Cells[i]
cell.CellFormat.Shading.BackgroundPatternColor = Color.get_LightGray()
cell.AddParagraph().AppendText(header)
office_supplies = [
["打印机", "PR-2024", "1599元"],
["碎纸机", "SH-2024", "399元"],
]
for row_idx, item in enumerate(office_supplies):
for col_idx, value in enumerate(item):
nested_table3.Rows[row_idx + 1].Cells[col_idx].AddParagraph().AppendText(value)
# 保存文档
document.SaveToFile("ProductCatalog.docx", FileFormat.Docx)
document.Close()
print("产品目录已创建完成")文档预览:

说明:
通过 cell.AddTable(True) 方法在单元格内创建嵌套表格。每个嵌套表格可以独立设置行数、列数和样式,非常适合展示具有层级关系的数据,如产品分类、部门组织结构等。
6. 技术细节总结与关键类方法概览
在前面的章节中,我们展示了如何使用 Free Spire.Doc for Python 创建基础表格、设置表格样式、合并与拆分单元格以及创建嵌套表格。从技术实现角度来看,Word 表格操作的核心流程可以总结为以下几个关键步骤:
Python Word 表格操作步骤总结
- 创建文档对象使用
Document()创建 Word 文档对象,通过AddSection()添加节,为表格提供容器。 - 创建表格使用
section.AddTable(True)创建表格,通过ResetCells()设置表格的行数和列数。 - 填充表格内容通过
table.Rows[row_index].Cells[col_index]访问单元格,使用AddParagraph().AppendText()方法添加文本内容。 - 设置单元格格式使用
CellFormat属性设置单元格的背景颜色、垂直对齐方式、边框等样式。 - 合并与拆分单元格使用
ApplyHorizontalMerge()和ApplyVerticalMerge()方法合并单元格,使用SplitCell()方法拆分单元格。 - 应用表格样式使用
ApplyStyle()应用预设的表格样式,或通过Format.Borders自定义边框样式。 - 保存文档使用
SaveToFile()方法将文档保存到指定路径。
关键类、方法与属性
| 类 / 方法 / 属性 | 说明 |
|---|---|
Document | Word 文档对象,支持创建、加载和保存文档 |
Document.SaveToFile() | 将文档保存到指定文件路径 |
Section | 表示文档中的节,是表格的容器对象 |
Table | 表示表格对象,包含行和单元格 |
Paragraph | 表示段落对象 |
TextRange.CharacterFormat | 获取文本格式对象,用于设置字体、大小、加粗等 |
通过理解上述关键类、方法和属性,你可以灵活地创建各种类型的 Word 表格,并根据业务需求进行精细定制。掌握这些技术细节,能让你在实际项目中快速生成高质量、格式统一的 Word 文档报表,同时保持代码简洁和可维护性。
总结
本文以实际业务场景为例,展示了如何使用 Free Spire.Doc for Python 在 Word 文档中创建基础表格、设置表格样式、合并与拆分单元格、创建嵌套表格等实用功能。通过编程方式生成表格,不仅避免了手动操作的繁琐和易错问题,还能轻松应对批量报告和复杂数据呈现需求。
掌握这一技能后,你可以将文档生成与数据管理完全自动化,从而节省时间,提高效率,并为业务流程提供可靠的文档支持。结合 Free Spire.Doc 的其他功能,如文档模板、邮件合并、图表插入等,可以进一步打造智能化的 Word 文档自动化工作流,让企业的文档处理能力提升到新的高度。
以上就是使用Python在Word文档中创建表格并设置各种格式的详细内容,更多关于Python Word创建表格并设置格式的资料请关注脚本之家其它相关文章!
相关文章
关于jupyter lab安装及导入tensorflow找不到模块的问题
这篇文章主要介绍了关于jupyter lab安装及导入tensorflow找不到模块的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-03-03


最新评论