python线条加粗_python docx 设置word表格边框(颜色/线型/粗细)

曾经在网上苦苦寻找过python docx对word表格边框的设置,一直没有,现在终于有了,包括边框颜色、线型、宽度粗细的设置,直接用这个函数set_cell_border就行了(附加office的参数参考),这是对单个单元格(cell)的上下左右四个边框进行设置的:

注意要提前安装python-docx模块呦,pip安装命令:pip install python-docx!

from docx.oxml import OxmlElement

from docx.oxml.ns import qn

def set_cell_border(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:

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]))

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值