Python中怎么用openpyxl为指定区域设置边框为粗匣框线

发布时间:2020-10-28 09:23:32 作者:小新
来源:亿速云 阅读:1815

小编给大家分享一下Python中怎么用openpyxl为指定区域设置边框为粗匣框线,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

举个简单的例子,就是这样:

Python中怎么用openpyxl为指定区域设置边框为粗匣框线

思路:openpyxl有一个border方法可以给单元格设置边框,同时需要设置上下左右四个方向。我们先得到这片区域的最外层的单元格们,分四个方向,我们给最左边一排的单元格设置左边框为粗线,其他三边为细线,其他三个方向的单元格方法一样。

代码示例:

import openpyxl from openpyxl.styles import Side, Border, colors #定义边框样式 def my_border(t_border, b_border, l_border, r_border):    border = Border(top=Side(border_style=t_border, color=colors.BLACK),                    bottom=Side(border_style=b_border, color=colors.BLACK),                    left=Side(border_style=l_border, color=colors.BLACK),                    right=Side(border_style=r_border, color=colors.BLACK))    return border #初始化制定区域边框为所有框线 def format_border(s_column, s_index, e_column , e_index):    for row in tuple(sheet[s_column + str(s_index):e_column + str(e_index)]):        for cell in row:            cell.border = my_border('thin', 'thin', 'thin', 'thin') #给指定区域设置粗匣框线 def set_solid_border(area_list):    for area in area_list:        s_column = area[0]        s_index = area[1]        e_column = area[2]        e_index = area[3]        #设置左粗框线        for cell in sheet[s_column][s_index - 1:e_index]:            cell.border = my_border(cell.border.top.style, cell.border.bottom.style,                                    'medium', cell.border.right.style)        # 设置右粗框线        for cell in sheet[e_column][s_index - 1:e_index]:            cell.border = my_border(cell.border.top.style, cell.border.bottom.style,                                    cell.border.left.style, 'medium')        # 设置上粗框线        for row in tuple(sheet[s_column + str(s_index):e_column + str(s_index)]):            for cell in row:                cell.border = my_border('medium', cell.border.bottom.style,                                        cell.border.left.style, cell.border.right.style)        # 设置下粗框线        for row in tuple(sheet[s_column + str(e_index):e_column + str(e_index)]):            for cell in row:                cell.border = my_border(cell.border.top.style, 'medium',                                        cell.border.left.style, cell.border.right.style) if __name__ == '__main__':    wb = openpyxl.load_workbook('test.xlsx')    sheet = wb['Sheet1']    format_border('A', 3, 'D', 10)    set_solid_border([['A', 3, 'D', 5], ['A', 6, 'D', 7], ['A', 8, 'D', 10],                      ['A', 3, 'A', 10], ['B', 3, 'C', 10], ['D', 3, 'D', 10]])    wb.save('test.xlsx')

运行结果如下:

Python中怎么用openpyxl为指定区域设置边框为粗匣框线

以上是Python中怎么用openpyxl为指定区域设置边框为粗匣框线的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. css如何设置table表格的边框为单线边框
  2. Sequoiadb中怎么指定OID为Date类型

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python openpyxl

上一篇:python获取当前时间日期的案例

下一篇:python正则表达式如何使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》