Applying borders to a cell in OpenPyxl

心已入冬 提交于 2019-11-30 08:36:28

With openpyxl version 2.2.5, this snippet works for me:

from openpyxl.styles.borders import Border, Side
from openpyxl import Workbook

thin_border = Border(left=Side(style='thin'), 
                     right=Side(style='thin'), 
                     top=Side(style='thin'), 
                     bottom=Side(style='thin'))

wb = Workbook()
ws = wb.get_active_sheet()
# property cell.border should be used instead of cell.style.border
ws.cell(row=3, column=2).border = thin_border
wb.save('border_test.xlsx')

With openpyxl version 2.0.4, this snippet works for me:

from openpyxl.styles.borders import Border, Side
from openpyxl.styles import Style
from openpyxl import Workbook

thin_border = Border(left=Side(style='thin'), 
                     right=Side(style='thin'), 
                     top=Side(style='thin'), 
                     bottom=Side(style='thin'))
my_style = Style(border=thin_border)

wb = Workbook()
ws = wb.get_active_sheet()
ws.cell(row=3, column=2).style = my_style
wb.save('border_test.xlsx')

This answer works with version 2.4.8 The difference with the previous two answers is that the property for Side is border_style, not style

from openpyxl.styles.borders import Border, Side, BORDER_THIN
thin_border = Border(
    left=Side(border_style=BORDER_THIN, color='00000000'),
    right=Side(border_style=BORDER_THIN, color='00000000'),
    top=Side(border_style=BORDER_THIN, color='00000000'),
    bottom=Side(border_style=BORDER_THIN, color='00000000')
)
ws.cell(row=3, column=2).border = thin_border

Working with styles: https://openpyxl.readthedocs.io/en/2.5/styles.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!