python-docx 默认模板内置了多种表格样式(如 'table grid'、'light shading' 等),但官方未提供直接枚举样式的 api;可通过遍历 `document.styles` 并筛选 `wd_style_type.table` 类型样式,结合动态生成示例表格实现可视化预览。
在使用 python-docx 创建 Word 文档时,为表格应用美观统一的样式是提升文档专业性的关键一步。虽然文档中常直接写死样式名(如 table.style = 'Table Grid'),但开发者往往不清楚当前环境支持哪些表格样式——尤其当基于不同模板(如自定义 .dotx 文件)运行时,可用样式可能变化。
幸运的是,python-docx 的 Document 对象包含完整的样式库(doc.styles),我们可通过类型过滤提取全部表格样式,并逐一渲染示例表格以直观对比效果。以下是完整实现方案:
from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.shared import Pt
def list_table_styles_to_doc(output_path='available_table_styles.docx'):
doc = Document()
# 获取所有表格样式(按名称排序,提升可读性)
table_styles = [
style for style in doc.styles
if style.type == WD_STYLE_TYPE.TABLE
]
table_styles.sort(key=lambda s: s.name)
# 为每个样式添加标题和示例表格
for i, style in enumerate(table_styles, 1):
# 标题:样式序号 + 名称
doc.add_heading(f'{i}. "{style.name}"', level=2)
# 创建 2×3 示例表格
table = doc.add_table(rows=2, cols=3, style=style)
table.autofit = False
table.allow_autofit = False
# 设置固定列宽(避免自动缩放干扰视觉判断)
for cell in table.columns[0].cells:
cell.width = Pt(120)
for cell in table.columns[1].cell
s:
cell.width = Pt(80)
for cell in table.columns[2].cells:
cell.width = Pt(140)
# 填充表头与示例数据
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Column A'
hdr_cells[1].text = 'Column B'
hdr_cells[2].text = 'Column C'
data_cells = table.rows[1].cells
data_cells[0].text = 'Data 1'
data_cells[1].text = 'Data 2'
data_cells[2].text = 'Data 3'
doc.save(output_path)
print(f"✅ 已生成包含 {len(table_styles)} 种表格样式的预览文档:{output_path}")
# 执行生成
list_table_styles_to_doc()⚠️ 注意事项:
运行上述脚本后,将生成一个 .docx 文件,其中每种表格样式均配有清晰编号与结构一致的示例表格,便于快速比对、选择与复用。这是在缺乏 GUI 样式面板的编程环境中,最可靠、可复现的样式探索方式。