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"},
)