在Openpyxl中设置样式

Nel*_*haw 42 python excel xlsx openpyxl

我需要在Openpyxl中设置样式的建议.

我看到可以设置单元格的NumberFormat,但我还需要设置字体颜色和属性(粗体等).有一个style.py类,但似乎我无法设置单元格的样式属性,我真的不想开始修改openpyxl源代码.

有没有人找到解决方案?

Mik*_*ton 81

从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
Run Code Online (Sandbox Code Playgroud)

仅供参考,您可以在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'
Run Code Online (Sandbox Code Playgroud)

  • 现在您可以添加字体颜色:_cell.style.font.color.index = Color.GREEN (8认同)
  • 无需修补openpyxl/style.py.只需在程序中定义类似"Color.Aquamarine ='007FFFD4'"的内容,然后使用...... = Color.Aquamarine (5认同)

Tom*_*yen 12

从openpyxl 2.0开始,设置单元格样式是通过创建新样式对象并将它们分配给单元格的属性来完成的.

有几种样式对象:Font,PatternFill,Border,和Alignment.见文档.

要更改单元格的样式属性,首先必须从单元格复制现有样式对象并更改属性的值,或者必须使用所需设置创建新样式对象.然后,将新样式对象分配给单元格.

将字体设置为单元格A1的粗体和斜体的示例:

from openpyxl import Workbook
from openpyxl.styles import Font
# Create workbook
wb = Workbook()
# Select active sheet
ws = wb.active()
# Select cell A1
cell = ws['A1']
# Make the text of the cell bold and italic
cell.font = cell.font.copy(bold=True, italic=True)
Run Code Online (Sandbox Code Playgroud)


use*_*614 11

从openpyxl 2.0开始,样式是不可变的.

如果您有cell,您可以(例如)通过以下方式设置粗体文本:

cell.style = cell.style.copy(font=cell.style.font.copy(bold=True))

是的,这很烦人.

  • 我尝试了这个并收到此错误: AttributeError: 'Font' object has no attribute 'copy' (2认同)

Par*_*ria 7

对于2.4.1和更高版本的openpyxl,请使用以下代码设置字体颜色:

from openpyxl.styles import Font
from openpyxl.styles.colors import Color

ws1['A1'].font = Font(color = "FF0000")
Run Code Online (Sandbox Code Playgroud)

各种颜色的十六进制代码可以在以下位置找到:http : //dmcritchie.mvps.org/excel/colors.htm


Ama*_*mar 6

2021 年新更新的 OpenPyXl 中更改字体的方法:

\n
sheet.cell.font = Font(size=23, underline='single', color='FFBB00', bold=True, italic=True)\n
Run Code Online (Sandbox Code Playgroud)\n

完整代码:

\n
import openpyxl  # Connect the library\nfrom openpyxl import Workbook\nfrom openpyxl.styles import PatternFill  # Connect cell styles\nfrom openpyxl.workbook import Workbook\nfrom openpyxl.styles import Font, Fill  # Connect styles for text\nfrom openpyxl.styles import colors  # Connect colors for text and cells\n\nwb = openpyxl.Workbook()  # Create book\nwork_sheet = wb.create_sheet(title='Testsheet')  # Created a sheet with a name and made it active\n\nwork_sheet['A1'] = 'Test text'\nwork_sheet_a1 = work_sheet['A5']  # Created a variable that contains cell A1 with the existing text\nwork_sheet_a1.font = Font(size=23, underline='single', color='FFBB00', bold=True,\n                          italic=True)  # We apply the following parameters to the text: size - 23, underline, color = FFBB00 (text color is specified in RGB), bold, oblique. If we do not need a bold font, we use the construction: bold = False. We act similarly if we do not need an oblique font: italic = False.\n\n# Important:\n# if necessary, the possibility of using standard colors is included in the styles, but the code in this case will look different:\nwork_sheet_a1.font = Font(size=23, underline='single', color=colors.RED, bold=True,\n                              italic=True)  # what color = colors.RED \xe2\x80\x94 color prescribed in styles\nwork_sheet_a1.fill = PatternFill(fill_type='solid', start_color='ff8327',\n                                 end_color='ff8327')  # This code allows you to do design color cells\n
Run Code Online (Sandbox Code Playgroud)\n


Don*_*kby 5

这似乎是一个已经改变了几次的功能。我使用的是 openpyxl 2.5.0,并且可以通过以下方式设置删除线选项:

new_font = copy(cell.font)
new_font.strike = True
cell.font = new_font
Run Code Online (Sandbox Code Playgroud)

似乎早期版本(1.9 到 2.4?)copy对字体有一个方法,但现在已弃用并发出警告:

cell.font = cell.font.copy(strike=True)
Run Code Online (Sandbox Code Playgroud)

1.8 之前的版本具有可变字体,因此您可以这样做:

cell.font.strike=True
Run Code Online (Sandbox Code Playgroud)

现在会引发错误。