之前我们完成了 Excel 数据提取、Word 表格写入与合并,现在继续 为 Word 表格添加高级样式 装扮,包括单元格边框、背景填色、居中对齐、粗体、高亮行/列等,进一步增强表格的可读性与专业性。
🖌️ 样式设置函数
1. 设置单元格边框
使用底层 XML 操作定制边框线条与样式:
from docx.table import _Cell
from docx.oxml import OxmlElement
from docx.oxml.ns import qndef Set_cell_border(cell: _Cell, **kwargs):"""为单个单元格定制边框(上/下/左/右以及内部边线)用法示例请见文末脚注。"""tc = cell._tctcPr = tc.get_or_add_tcPr()tcBorders = tcPr.first_child_found_in("w:tcBorders")if tcBorders is None:tcBorders = OxmlElement('w:tcBorders')tcPr.append(tcBorders)for edge in ('start','top','end','bottom','insideH','insideV'):edge_data = kwargs.get(edge)if edge_data:tag = f"w:{edge}"elm = tcBorders.find(qn(tag)) or OxmlElement(tag)if elm.parent is None:tcBorders.append(elm)for key in ("sz","val","color","space","shadow"):if key in edge_data:elm.set(qn(f"w:{key}"), str(edge_data[key]))
-
可设置线宽 (
sz
)、线型 (val
)、颜色 (color
)、阴影 (shadow
) 等; -
仿照社区推荐函数 blog.csdn.netzenn.dev+4stackoverflow.com+4blog.csdn.net+4。
2. 设置单元格背景色
from docx.oxml import parse_xml
from docx.oxml.ns import nsdeclsdef Set_Background_Color(cell, rgbColor):"""为单元格填充背景色,使用 RGB 6 位十六进制格式。"""shading = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{rgbColor}"/>')cell._tc.get_or_add_tcPr().append(shading)
通过 XML 指定 w:shd
节点,完成底色设置,常用来高亮重要数据行。
🎯 实战样式增强步骤
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.shared import Cm
from docx import Documentdoc = Document("收货记录.docx")
table = doc.tables[0]
max_row = len(table.rows)# 1️⃣ 最后一行“总数”字体加粗、行高调大
run = table.cell(max_row-1, 4).paragraphs[0].runs[0]
run.font.bold = True
table.rows[max_row-1].height = Cm(1)# 2️⃣ 去掉最后一行空白单元格边框
for c in [0,1,2,3,6]:Set_cell_border(table.cell(max_row-1, c), bottom={"color":"#FFFFFF"}, start={"color":"#FFFFFF"}, end={"color":"#FFFFFF"})# 3️⃣ 全表内容水平 & 垂直居中
for r in range(1, max_row):for c in range(len(table.columns)):cell = table.cell(r,c)cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTERcell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER# 4️⃣ 数量 ≥85 的单元格底色高亮
qty_values = [int(table.rows[i].cells[5].text) for i in range(1, max_row-1)]
for i, qty in enumerate(qty_values, start=1):if qty >= 85:Set_Background_Color(table.cell(i,5), "98F5FF")doc.save("收货记录-整理.docx")
🖼️ 结果展示区
✅ 补充说明
-
边框函数可执行细粒度控制,适配自定义边框样式 discuss.python.org+3github.com+3python-docx.readthedocs.io+3python-docx.readthedocs.io+8stackoverflow.com+8zenn.dev+8discuss.python.orgblog.csdn.net+1python-docx.readthedocs.io+1python-docx.readthedocs.iopython-docx.readthedocs.io;
-
居中对齐函数依赖
WD_ALIGN_PARAGRAPH.CENTER
和WD_ALIGN_VERTICAL.CENTER
; -
设置行高使用
Cm
单位,在不同纸张环境下表现稳定; -
背景色函数适用于高亮关键行或列,增强视觉效果;
-
可扩展方向:设置字体颜色、单元格宽度、条件样式规则等。
更多实用案例,代码,素材如下:
自取链接:https://pan.quark.cn/s/a46f30accea2
👇 总结
通过本篇教程,你摸索到:
-
使用
python-docx
操控 Word 表格样式; -
如何设置单元格边框、背景色、居中、加粗等格式;
-
将原始数据美化为专业报表,适合收货/发票/统计记录等场景;
-
可自由扩展样式函数与模板,生成图文并茂的 Word 报表。
如果你希望加封面页、页脚页码、样式模板批量套用等功能,可以继续告诉我,我可以帮你把这套工具包完善成一个完整的办公自动化链!