Val*_*tin 9 python docx python-docx
我需要使用python-docx在表格中设置单元格边框,但找不到如何操作.请帮忙.
Iul*_*ana 10
看一下git上发布的问题.
您可以使用一些默认的表格样式:
table = document.add_table(rows, cols)
table.style = 'TableGrid'
Run Code Online (Sandbox Code Playgroud)
这是我在其中一个项目中使用的代码段。也适用于合并的单元格。
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
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"},
start={"sz": 24, "val": "dashed", "shadow": "true"},
end={"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 ('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 one
element = tcBorders.find(qn(tag))
if element is None:
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]))
Run Code Online (Sandbox Code Playgroud)
检查http://officeopenxml.com/WPtableBorders.php以获取可用的属性值
小智 5
table = document.add_table(rows, cols)
table.style = 'Table Grid'
Run Code Online (Sandbox Code Playgroud)
不建议将style与一起使用,TableGrid因为style ID已弃用。现在我们需要使用名称:
table.style = 'Table Grid'
| 归档时间: |
|
| 查看次数: |
10436 次 |
| 最近记录: |