栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python】openpyxl设置excel的表格边框内外边框不同处理

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Python】openpyxl设置excel的表格边框内外边框不同处理

使用的是openpyxl,如下代码可以实现内外边框不同处理
外部是加粗格式,内部是虚线格式

参数介绍:

ws: Excel的sheet页
start_row:  开始行(数字)
end_row: 结束行(数字)
start_col: 开始列(数字)
end_col: 结束列(数字)

代码:

# ボーダー設定
def format_border(ws, start_row, end_row, start_col, end_col):
    # 内部ボーダー
    for row in tuple(ws[start_row:end_row]):
        for cell in row[start_col-1:end_col]:
            cell.border = set_border('dotted', 'dotted', 'dotted', 'dotted')
    # 左側ボーダー
    for cell in [row[start_col-1] for row in ws[start_row:end_row]]:
        cell.border = set_border(cell.border.top.style, cell.border.bottom.style, 'medium', cell.border.right.style)
    # 右側ボーダー
    for cell in [row[end_col-1] for row in ws[start_row:end_row]]:
        cell.border = set_border(cell.border.top.style, cell.border.bottom.style, cell.border.left.style, 'medium')
    # 上側ボーダー
    for cell in ws[start_row][start_col-1:end_col]:
        cell.border = set_border('medium', cell.border.bottom.style, cell.border.left.style, cell.border.right.style)
    # 下側ボーダー
    for cell in ws[end_row][start_col-1:end_col]:
        cell.border = set_border(cell.border.top.style, 'medium', cell.border.left.style, cell.border.right.style)
    return ws

# 定義ボーダー様式
def set_border(t_border, b_border, l_border, r_border, t_color='000000', b_color='000000', l_color='000000', r_color='000000'):
    border = Border(top=Side(border_style=t_border, color=t_color),
                    bottom=Side(border_style=b_border, color=b_color),
                    left=Side(border_style=l_border, color=l_color),
                    right=Side(border_style=r_border, color=r_color))
    return border

效果图:


ps:如果要同时设置边框的颜色,可以通过修改color值,如果是需要保持原来的颜色,可以使用如下代码,可以在修改边框颜色的同时,保持原来的样式

cell.border = set_border(cell.border.top.style, 'dotted', cell.border.left.style, cell.border.right.style, t_color=cell.border.top.color, b_color='0000ff', l_color=cell.border.left.color, r_color=cell.border.right.color)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/324107.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号