python-docx 設定Table 邊框樣式、單元格邊框樣式
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
from docx.table import _Cell
# 設定 table 的邊框,用法與 cell 類似
def set_table_boarder(table, **kwargs):
"""
Set table`s border
Usage:
set_table_border(
cell,
top={"sz": 12, "val": "single", "color": "#FF0000"},
bottom={"sz": 12, "color": "#00FF00", "val": "single"},
left={"sz": 24, "val": "dashed"},
right={"sz": 12, "val": "dashed"},
)
"""
borders = OxmlElement('w:tblBorders')
for tag in ('bottom', 'top', 'left', 'right', 'insideV', 'insideH'):
edge_data = kwargs.get(tag)
if edge_data:
any_border = OxmlElement(f'w:{tag}')
for key in ["sz", "val", "color", "space", "shadow"]:
if key in edge_data:
any_border.set(qn(f'w:{key}'), str(edge_data[key]))
borders.append(any_border)
table._tbl.tblPr.append(borders)
# 将table 的所有單元格四個邊設定為 0.5 鎊, 黑色, 實線
def set_table_singleBoard(table): return set_table_boarder(
table,
top={"sz": 4, "val": "single", "color": "#000000"},
bottom={"sz": 4, "val": "single", "color": "#000000"},
left={"sz": 4, "val": "single", "color": "#000000"},
right={"sz": 4, "val": "single", "color": "#000000"},
insideV={"sz": 4, "val": "single", "color": "#000000"},
insideH={"sz": 4, "val": "single", "color": "#000000"}
)
以下函數引用自[https://blog.csdn.net/weixin_44312186/article/details/104944110] 修改 start 為 left, end 為 right進而能夠設定左右邊框
def set_cell_border(cell: _Cell, **kwargs):
"""
Set cell`s border
Usage:
set_cell_border(
cell,
top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
bottom={"sz": 12, "color": "#00FF00", "val": "single"},
left={"sz": 24, "val": "dashed", "shadow": "true"},
right={"sz": 12, "val": "dashed"},
)
"""
tc = cell._tc
tcPr = tc.get_or_add_tcPr()
# check for tag existnace, if none found, then create one
tcBorders = tcPr.first_child_found_in("w:tcBorders")
if tcBorders is None:
tcBorders = OxmlElement('w:tcBorders')
tcPr.append(tcBorders)
# list over all available tags
for edge in ('left', 'top', 'right', 'bottom', 'insideH', 'insideV'):
edge_data = kwargs.get(edge)
if edge_data:
tag = 'w:{}'.format(edge)
# check for tag existnace, if none found, then create one
element = tcBorders.find(qn(tag))
if element is None:
print(tag)
element = OxmlElement(tag)
tcBorders.append(element)
# looks like order of attributes is important
for key in ["sz", "val", "color", "space", "shadow"]:
if key in edge_data:
element.set(qn('w:{}'.format(key)), str(edge_data[key]))
以下lambda 函數簡化 set_cell_boarder 的使用
# 将cell 的四個邊設定為 0.5 鎊, 黑色, 實線
def set_cell(cell): return set_cell_border(
cell,
top={"sz": 6, "val": "single", "color": "#000000", "space": "0"},
bottom={"sz": 6, "val": "single", "color": "#000000", "space": "0"},
left={"sz": 6, "val": "single", "color": "#000000"},
right={"sz": 6, "val": "single", "color": "#000000"},
insideV={"sz": 6, "val": "single"},
insideH={"sz": 6, "val": "single"},
)