1.在用python-docx库插入表格后,想要更改表格样式可以通过表格样式来更改,比如:设为无线框表格
table_style = 'Normal Table'
这种方法在网上一堆,便不再赘述。但这种方法很“死板”,只能选取docx库中的指定样式,做不到根据要求隐去表格的某条边框,要实现此功能,只能自己写。
2.python-docx库官方目前没有设置单元格边框的函数方法,可以使用下列代码进行每个单元格边框的设置,用法见函数中‘Usage’字段。
from docx.table import _Cellfrom docx.oxml import OxmlElementfrom docx.oxml.ns import qndef set_cell_border(cell: _Cell, **kwargs):"""Set cell`s borderUsage:set_cell_border(cell,top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},bottom={"sz": 12, "color": "#00FF00", "val": "single"},start={"sz": 24, "val": "dashed", "shadow": "true"},end={"sz": 12, "val": "dashed"},)"""tc = cell._tctcPr = tc.get_or_add_tcPr()# check for tag existnace, if none found, then create onetcBorders = tcPr.first_child_found_in("w:tcBorders")if tcBorders is None:tcBorders = OxmlElement('w:tcBorders')tcPr.append(tcBorders)# list over all available tagsfor edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):edge_data = kwargs.get(edge)if edge_data:tag = 'w:{}'.format(edge)# check for tag existnace, if none found, then create oneelement = tcBorders.find(qn(tag))if element is None:element = OxmlElement(tag)tcBorders.append(element)# looks like order of attributes is importantfor key in ["sz", "val", "color", "space", "shadow"]:if key in edge_data:element.set(qn('w:{}'.format(key)), str(edge_data[key]))
3. Check/WPtableBorders.phpfor available attributes values
Elements:
Reference:ECMA-376, 3rd Edition (June, ), Fundamentals and Markup Language Reference § 17.4.80.
Attributes of child elements:
The most commonly used attributes are below. (The theme-related and frame attributes have been omitted.)