使用Openpyxl将边界应用于单元格区域

时间:2015-12-29 23:30:56

标签: python excel openpyxl

我使用的是python 2.7.10和openpyxl 2.3.2,我是一个Python新手。

我正在尝试将边框应用于Excel工作表中的指定范围的单元格(例如C3:H10)。我在下面的尝试失败,并显示以下消息:

  

AttributeError:'Cell'对象没有属性'styles'。

如何将边框附加到单元格?任何见解都会感激不尽。

我目前的代码:

import openpyxl
from openpyxl.styles import Border, Side

def set_border(ws, cell_range):
    rows = ws.iter_rows(cell_range)
    for row in rows:
        row[0].styles.borders = Border(left=Side(border_style='thin', color="FF000000"))
        row[-1].styles.borders = Border(right=Side(border_style='thin', color="FF000000"))
    for c in rows[0]:
        c.styles.borders = Border(top=Side(border_style='thin', color="FF000000"))
    for c in rows[-1]:
        c.styles.borders = Border(bottom=Side(border_style='thin', color="FF000000"))


# Example call to set_border
wb = openpyxl.load_workbook('example.xlsx')
ws = wb.get_sheet_by_name('Sheet1')

set_border(ws, "B3:H10")

2 个答案:

答案 0 :(得分:10)

首先,属性称为style(不是styles)和border(不是borders)。另外,要更改边框,您应直接设置cell.border

除了你在边界逻辑方面存在一些问题之外,由于迭代器和角点,使它正常工作会更复杂。这是一个粗略的版本(它很简单,我可以得到它,但不是内存效率):

def set_border(ws, cell_range):
    rows = ws[cell_range]
    side = Side(border_style='thin', color="FF000000")

    rows = list(rows)  # we convert iterator to list for simplicity, but it's not memory efficient solution
    max_y = len(rows) - 1  # index of the last row
    for pos_y, cells in enumerate(rows):
        max_x = len(cells) - 1  # index of the last cell
        for pos_x, cell in enumerate(cells):
            border = Border(
                left=cell.border.left,
                right=cell.border.right,
                top=cell.border.top,
                bottom=cell.border.bottom
            )
            if pos_x == 0:
                border.left = side
            if pos_x == max_x:
                border.right = side
            if pos_y == 0:
                border.top = side
            if pos_y == max_y:
                border.bottom = side

            # set new border only if it's one of the edge cells
            if pos_x == 0 or pos_x == max_x or pos_y == 0 or pos_y == max_y:
                cell.border = border

答案 1 :(得分:0)

border = Border(
            left=cell.border.left,
            right=cell.border.right,
            top=cell.border.top,
            bottom=cell.border.bottom)

可以替换为:

border = cell.border.copy()

PS:你的回答帮助了我......