Applying borders to a cell in OpenPyxl

穿精又带淫゛_ 提交于 2019-11-29 12:42:02

问题


I am trying to use Openpyxl to apply a border to a cell, but I have failed on the most basic "apply any kind of border to any cell anywhere" task. I tried copying from the Openpyxl documentation (http://pythonhosted.org/openpyxl/styles.html#introduction) default style and modifying, but that gives me

"TypeError:init() got an unexpected keyword argument 'superscript'"

I tried copying straight out of another example here (Apply borders to all cells in a range with openpyxl), but that gives me

AttributeError: type object 'Border' has no attribute 'BORDER_THIN'

(even after I fix the typos and insufficient imports errors).

Does anyone know how to apply borders using Python 3.3 and OpenPyxl 2.0.4? All I'm looking for is a snippet of code that, if I copy-paste it into a blank script, will put a border around any cell in a workbook.


回答1:


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')

The documentation mentions other values for the style attribute :

Value must be one of {‘double’, ‘dashed’, ‘thin’, ‘medium’, ‘mediumDashDot’, ‘dashDot’, ‘thick’, ‘mediumDashed’, ‘hair’, ‘dotted’, ‘slantDashDot’, ‘mediumDashDotDot’, ‘dashDotDot’}




回答2:


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')



回答3:


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



来源:https://stackoverflow.com/questions/24917201/applying-borders-to-a-cell-in-openpyxl

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