之前我們完成了 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 報表。
如果你希望加封面頁、頁腳頁碼、樣式模板批量套用等功能,可以繼續告訴我,我可以幫你把這套工具包完善成一個完整的辦公自動化鏈!