使用openpyxl给工作表指定区域添加外边框

利用openpyxl为工作表指定区域添加边框

  • openpyxl的边框功能
  • 为指定单元格添加边框
  • 局限性
  • 指定区域添加边框的实现
  • openpyxl的边框功能

    openpyxl库提供了针对excel中某单元格的的一系列操作:包括字体、颜色、填充、边框、对齐等。具体功能见官方文档:

    https://openpyxl.readthedocs.io/en/stable/styles.html

    为指定单元格添加边框

    导入openpyxl库:
    (若未安装可以通过在python目录下执行pip install openpyxl命令安装)

    from openpyxl import Workbook,load_workbook
    from openpyxl.styles import *
    

    读取excel文件

    wb = load_workbook('46_data.xlsx')      #读取excel文件
    sheet_name = 'Sheet1'
    ws = wb[sheet_name]                     #ws是待操作的工作表
    

    为C3单元格添加粗外边框

    ws['C3'].border = Border(left=Side(style='thick'),bottom=Side(style='thick'),right=Side(style='thick'),top=Side(style='thick'))
    

    或:

    ws.cell(3,3).border = Border(left=Side(style='thick'),bottom=Side(style='thick'),right=Side(style='thick'),top=Side(style='thick'))
    

    效果如下:

    局限性

    通过直接调用或者是.cell方式调用,得到的都是一个cell对象:

    print(ws['C3'])
    print(type(ws['C3']))
    print(ws.cell(3,3))
    print(type(ws.cell(3,3)))
    

    输出结果
    但如果输出某个区域(不止一个单元格)的cell对象,利用同样的方式却变成一个元组:

    print(ws['A1:D5'])
    print(type(ws['A1:D5']))
    


    利用同样的方式添加边框时,会报错,原因是元组没有border属性。

    想要整体添加边框,有如下两种方式:(2022.1.30更新)

    1. 先合并单元格再进行操作,但往往这些单元格都有不同的数据,难以进行合并。
    2. 遍历元组中的所有cell,分别赋予属性。这种方法比较适用于为所有的单元格赋予相同的属性。如下代码所示:
    area = ws['A1:D5']
    for i in area:
        for j in i:
            j.border = Border(right=Side(style='thick'),bottom=Side(style='thick'))
    

    但由于外边框的操作比较特殊,各个单元格需要赋予的属性不相同,而且大部分单元格不需要操作。

    基于以上分析,拟采用直接操作相应单元格的方式实现目标。

    指定区域添加边框的实现

    通过自己写一个filling()功能来完成指定区域的边框添加:

    def filling(start_loc,end_loc,ws):         #参数为左上角坐标和右下角坐标,形如'D3','A5'等。ws是worksheet对象。
        x_start = start_loc[0]
        y_start = start_loc[1:len(start_loc)]   #切片获取坐标的数字部分
        x_end = end_loc[0]
        y_end = end_loc[1:len(end_loc)]   
        len_y = int(y_end) - int(y_start) + 1
        alphabet = string.ascii_uppercase        #导入字母表
        len_x = alphabet.index(x_end) - alphabet.index(x_start) + 1
        # 左上
        temp = start_loc
        ws[temp].border = Border(left=Side(style='thick'),top=Side(style='thick'))
        # 右下
        temp = end_loc
        ws[temp].border = Border(right=Side(style='thick'),bottom=Side(style='thick'))
        # 右上
        temp = x_end + y_start
        ws[temp].border = Border(right=Side(style='thick'),top=Side(style='thick'))
        # 左下
        temp = x_start + y_end
        ws[temp].border = Border(left=Side(style='thick'),bottom=Side(style='thick'))
        # 上
        for i in range(0,len_x-2):
            temp = alphabet[alphabet.index(x_start)+1+i] + y_start
            ws[temp].border = Border(top=Side(style='thick'))
        # 下
        for i in range(0,len_x-2):
            temp = alphabet[alphabet.index(x_start)+1+i] + y_end
            ws[temp].border = Border(bottom=Side(style='thick'))
        # 左
        for i in range(0,len_y-2):
            temp = x_start + str(int(y_start) + 1 + i)
            ws[temp].border = Border(left=Side(style='thick'))
        # 右
        for i in range(0,len_y-2):
            temp = x_end + str(int(y_start) + 1 + i)
            ws[temp].border = Border(right=Side(style='thick'))
        return 0
    

    通过调用该函数,实现了B3到G8区域粗外边框的添加

    filling('B3','G8',ws)
    

    2022.1.30更新:

    注意到:由于其中字母表是从string库中获取的,长度只有26:

  • alphabet = string.ascii_uppercase
  • 输出为:‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’
  • 所以这种方式只能实现A~Z列范围内的操作。
    如果需要拓展到更多列中,可能有如下2种方法:

    1. 将excel的列索引改为数字,但不清楚openpyxl能否使用数字列索引;
    2. 用其他方法导入包含形如’AB’,'BG’这样双字符索引的字母库;

    感觉A~Z范围内就足够日常处理表格用了,毕竟是一个工具,方便为主。所以就不作进一步探究了,有兴趣的朋友可以继续研究!欢迎交流。

    物联沃分享整理
    物联沃-IOTWORD物联网 » 使用openpyxl给工作表指定区域添加外边框

    发表评论