0
点赞
收藏
分享

微信扫一扫

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

ZSACH 2022-01-31 阅读 57
pythonexcel

利用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属性。
在这里插入图片描述

想要整体添加边框,必须先合并单元格再进行操作,但往往这些单元格都有不同的数据,无法进行合并。

指定区域添加边框的实现

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

def filling(start_loc,end_loc,ws):         #参数为左上角坐标和右下角坐标,形如'D3','A5'等。ws是worksheet对象。
    x_start = start_loc[0]
    y_start = start_loc[1]
    x_end = end_loc[0]
    y_end = end_loc[1]
    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)

在这里插入图片描述

举报

相关推荐

0 条评论