在Openpyxl中设置样式
我需要一些关于在Openpyxl中设置样式的建议。
我看到可以设置单元格的数字格式,但我还想设置字体颜色和一些属性(比如加粗等)。虽然有一个style.py的类,但我似乎无法设置单元格的样式属性,而且我也不想去动Openpyxl的源代码。
有没有人找到解决办法呢?
10 个回答
15
从 openpyxl 2.0 开始,样式是不可改变的。
如果你有一个 cell
(单元格),你可以通过以下方式来设置文本为粗体:
cell.style = cell.style.copy(font=cell.style.font.copy(bold=True))
没错,这确实让人觉得麻烦。
18
对于openpyxl版本2.4.1及以上,使用下面的代码来设置字体颜色:
from openpyxl.styles import Font
from openpyxl.styles.colors import Color
ws1['A1'].font = Font(color = "FF0000")
各种颜色的十六进制代码可以在这里找到: http://dmcritchie.mvps.org/excel/colors.htm
85
从openpyxl版本1.5.7开始,我成功地应用了以下工作表样式选项...
from openpyxl.reader.excel import load_workbook
from openpyxl.workbook import Workbook
from openpyxl.styles import Color, Fill
from openpyxl.cell import Cell
# Load the workbook...
book = load_workbook('foo.xlsx')
# define ws here, in this case I pick the first worksheet in the workbook...
# NOTE: openpyxl has other ways to select a specific worksheet (i.e. by name
# via book.get_sheet_by_name('someWorksheetName'))
ws = book.worksheets[0]
## ws is a openpypxl worksheet object
_cell = ws.cell('C1')
# Font properties
_cell.style.font.color.index = Color.GREEN
_cell.style.font.name = 'Arial'
_cell.style.font.size = 8
_cell.style.font.bold = True
_cell.style.alignment.wrap_text = True
# Cell background color
_cell.style.fill.fill_type = Fill.FILL_SOLID
_cell.style.fill.start_color.index = Color.DARKRED
# You should only modify column dimensions after you have written a cell in
# the column. Perfect world: write column dimensions once per column
#
ws.column_dimensions["C"].width = 60.0
顺便提一下,你可以在openpyxl/style.py
中找到颜色的名称... 有时候我会从X11颜色名称中添加一些额外的颜色
class Color(HashableObject):
"""Named colors for use in styles."""
BLACK = 'FF000000'
WHITE = 'FFFFFFFF'
RED = 'FFFF0000'
DARKRED = 'FF800000'
BLUE = 'FF0000FF'
DARKBLUE = 'FF000080'
GREEN = 'FF00FF00'
DARKGREEN = 'FF008000'
YELLOW = 'FFFFFF00'
DARKYELLOW = 'FF808000'