在OpenPyxl中对单元格应用边框 [英] Applying borders to a cell in OpenPyxl

查看:152
本文介绍了在OpenPyxl中对单元格应用边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Openpyxl将边框应用于单元格,但在最基本的将任何类型的边框应用于任何单元格的任何位置"任务上,我都失败了.我尝试从Openpyxl文档中复制( http://pythonhosted.org/openpyxl/styles.html#introduction )的默认样式并进行修改,但这给了我

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 ()获得了意外的关键字参数'上标'"

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

我尝试直接复制另一个示例(对使用openpyxl的范围中的所有单元格应用边框),但这给了我

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

AttributeError:类型对象'Border'没有属性'BORDER_THIN'

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

(即使在我修正了输入错误和导入错误之后).

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

有人知道如何使用Python 3.3和OpenPyxl 2.0.4应用边框吗?我要寻找的只是一小段代码,如果我将其复制粘贴到空白脚本中,则会在工作簿中的任何单元格周围放置边框.

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.

推荐答案

在openpyxl 2.2.5版中,此代码段对我有用:

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

文档中提到了样式属性的其他值:

值必须为{"double","dashed","thin","medium", "mediumDashDot","dashDot","thick","mediumDashed","hair","dotted", ‘slantDashDot’,‘mediumDashDotDot’,‘dashDotDot’}

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

这篇关于在OpenPyxl中对单元格应用边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆