✨ Python 高级定制 | 美化 Word 表格边框与样式(收货记录增强版)

发布于:2025-07-01 ⋅ 阅读:(21) ⋅ 点赞:(0)

之前我们完成了 Excel 数据提取、Word 表格写入与合并,现在继续 为 Word 表格添加高级样式 装扮,包括单元格边框、背景填色、居中对齐、粗体、高亮行/列等,进一步增强表格的可读性与专业性。


🖌️ 样式设置函数

1. 设置单元格边框

使用底层 XML 操作定制边框线条与样式:

from docx.table import _Cell
from docx.oxml import OxmlElement
from docx.oxml.ns import qn

def Set_cell_border(cell: _Cell, **kwargs):
    """
    为单个单元格定制边框(上/下/左/右以及内部边线)
    用法示例请见文末脚注。
    """
    tc = cell._tc
    tcPr = 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]))

2. 设置单元格背景色

from docx.oxml import parse_xml
from docx.oxml.ns import nsdecls

def 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 Document

doc = 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.CENTER
        cell.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")

🖼️ 结果展示区 

 

✅ 补充说明

 更多实用案例,代码,素材如下:

自取链接:https://pan.quark.cn/s/a46f30accea2

👇 总结

通过本篇教程,你摸索到:

  • 使用 python-docx 操控 Word 表格样式;

  • 如何设置单元格边框、背景色、居中、加粗等格式;

  • 将原始数据美化为专业报表,适合收货/发票/统计记录等场景;

  • 可自由扩展样式函数与模板,生成图文并茂的 Word 报表。

如果你希望加封面页、页脚页码、样式模板批量套用等功能,可以继续告诉我,我可以帮你把这套工具包完善成一个完整的办公自动化链!


网站公告

今日签到

点亮在社区的每一天
去签到