在 Openpyxl 中设置样式

发布于 2024-12-20 08:15:47 字数 168 浏览 7 评论 0原文

我需要有关在 Openpyxl 中设置样式的建议。

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

有没有人找到解决这个问题的方法?

I need advice on setting styles in Openpyxl.

I see that the NumberFormat of a cell can be set, but I also require setting of font colors and attributes (bold etc). There is a style.py class but it seems I can't set the style attribute of a cell, and I don't really want to start tinkering with the openpyxl source code.

Has anyone found a solution to this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

过去的过去 2024-12-27 08:15:47

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

As of openpyxl version 1.5.7, I have successfully applied the following worksheet style options...

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

FYI, you can find the names of the colors in openpyxl/style.py... I sometimes I patch in extra colors from the X11 color names

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'
冷情 2024-12-27 08:15:47

对于 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

For openpyxl version 2.4.1 and above use below code to set font color:

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

ws1['A1'].font = Font(color = "FF0000")

hex codes for various colors can be found at:
http://dmcritchie.mvps.org/excel/colors.htm

乖乖哒 2024-12-27 08:15:47

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

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

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

是的,这很烦人。

As of openpyxl 2.0, styles are immutable.

If you have a cell, you can (e.g.) set bold text by:

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

Yes, this is annoying.

拒绝两难 2024-12-27 08:15:47

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

有多种样式对象:FontPatternFillBorderAlignment。请参阅文档

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

将单元格 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)

As of openpyxl 2.0, setting cell styles is done by creating new style objects and by assigning them to properties of a cell.

There are several style objects: Font, PatternFill, Border, and Alignment. See the doc.

To change a style property of a cell, first you either have to copy the existing style object from the cell and change the value of the property or you have to create a new style object with the desired settings. Then, assign the new style object to the cell.

Example of setting the font to bold and italic of cell 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)
始终不够 2024-12-27 08:15:47

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

sheet.cell.font = Font(size=23, underline='single', color='FFBB00', bold=True, italic=True)

完整代码:

import openpyxl  # Connect the library
from openpyxl import Workbook
from openpyxl.styles import PatternFill  # Connect cell styles
from openpyxl.workbook import Workbook
from openpyxl.styles import Font, Fill  # Connect styles for text
from openpyxl.styles import colors  # Connect colors for text and cells

wb = openpyxl.Workbook()  # Create book
work_sheet = wb.create_sheet(title='Testsheet')  # Created a sheet with a name and made it active

work_sheet['A1'] = 'Test text'
work_sheet_a1 = work_sheet['A5']  # Created a variable that contains cell A1 with the existing text
work_sheet_a1.font = Font(size=23, underline='single', color='FFBB00', bold=True,
                          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.

# Important:
# if necessary, the possibility of using standard colors is included in the styles, but the code in this case will look different:
work_sheet_a1.font = Font(size=23, underline='single', color=colors.RED, bold=True,
                              italic=True)  # what color = colors.RED — color prescribed in styles
work_sheet_a1.fill = PatternFill(fill_type='solid', start_color='ff8327',
                                 end_color='ff8327')  # This code allows you to do design color cells

New 2021 Updated Way of Changing FONT in OpenPyXl:

sheet.cell.font = Font(size=23, underline='single', color='FFBB00', bold=True, italic=True)

Full Code:

import openpyxl  # Connect the library
from openpyxl import Workbook
from openpyxl.styles import PatternFill  # Connect cell styles
from openpyxl.workbook import Workbook
from openpyxl.styles import Font, Fill  # Connect styles for text
from openpyxl.styles import colors  # Connect colors for text and cells

wb = openpyxl.Workbook()  # Create book
work_sheet = wb.create_sheet(title='Testsheet')  # Created a sheet with a name and made it active

work_sheet['A1'] = 'Test text'
work_sheet_a1 = work_sheet['A5']  # Created a variable that contains cell A1 with the existing text
work_sheet_a1.font = Font(size=23, underline='single', color='FFBB00', bold=True,
                          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.

# Important:
# if necessary, the possibility of using standard colors is included in the styles, but the code in this case will look different:
work_sheet_a1.font = Font(size=23, underline='single', color=colors.RED, bold=True,
                              italic=True)  # what color = colors.RED — color prescribed in styles
work_sheet_a1.fill = PatternFill(fill_type='solid', start_color='ff8327',
                                 end_color='ff8327')  # This code allows you to do design color cells
腹黑女流氓 2024-12-27 08:15:47

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

new_font = copy(cell.font)
new_font.strike = True
cell.font = new_font

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

cell.font = cell.font.copy(strike=True)

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

cell.font.strike=True

现在会引发错误。

This seems like a feature that has changed a few times. I am using openpyxl 2.5.0, and I was able to set the strike-through option this way:

new_font = copy(cell.font)
new_font.strike = True
cell.font = new_font

It seems like earlier versions (1.9 to 2.4?) had a copy method on the font that is now deprecated and raises a warning:

cell.font = cell.font.copy(strike=True)

Versions up to 1.8 had mutable fonts, so you could just do this:

cell.font.strike=True

That now raises an error.

渔村楼浪 2024-12-27 08:15:47

就像 openpyxl doc 所说:

这是一个开源项目,由志愿者在业余时间维护。这很可能意味着缺少您想要的特定特性或功能。

我检查了openpyxl源代码,发现:

直到openpyxl 1.8.x,样式都是可变的。它们的属性可以像这样直接分配:

from openpyxl.workbook import Workbook
from openpyxl.style import Color

wb = Workbook()
ws = wb.active
ws['A1'].style.font.color.index = Color.RED

但是从 openpyxl 1.9 开始,样式是不可变的。

样式在对象之间共享,一旦指定,就无法更改。这可以阻止不需要的副作用,例如更改大量单元格的样式,而不是仅更改一个单元格的样式。

要创建新的样式对象,可以直接分配它,或者从现有单元格的样式中复制一个具有新属性的样式,以回答问题为例(请原谅我的中文英语):

from openpyxl.styles import colors
from openpyxl.styles import Font, Color
from openpyxl import Workbook
wb = Workbook()
ws = wb.active

a1 = ws['A1']
d4 = ws['D4']

# create a new style with required attributes
ft_red = Font(color=colors.RED) 
a1.font = ft_red

# you can also do it with function copy
ft_red_bold = ft_red.copy(bold=True)

# you can copy from a cell's style with required attributes
ft_red_sigle_underline = a1.font.copy(underline="single")

d4.font = ft_red_bold

# apply style to column E
col_e = ws.column_dimensions['E']
col_e.font = ft_red_sigle_underline

单元格的样式包含这些属性:字体,填充、边框、对齐、保护和数字格式。检查openpyxl.styles

它们很相似,都应该创建为一个对象,除了number_format,它的值是string类型。

可以使用一些预定义的数字格式,也可以在字符串类型中定义数字格式。检查openpyxl.styles.numbers

from openpyxl.styles import numbers

# use pre-defined values
ws.cell['T49'].number_format = numbers.FORMAT_GENERAL
ws.cell(row=2, column=4).number_format = numbers.FORMAT_DATE_XLSX15

# use strings
ws.cell['T57'].number_format = 'General'
ws.cell(row=3, column=5).number_format = 'd-mmm-yy'
ws.cell['E5'].number_format = '0.00'
ws.cell['E50'].number_format = '0.00%'
ws.cell['E100'].number_format = '_ * #,##0_ ;_ * -#,##0_ ;_ * "-"??_ ;_ @_ '

Like openpyxl doc said:

This is an open source project, maintained by volunteers in their spare time. This may well mean that particular features or functions that you would like are missing.

I checked openpyxl source code, found that:

Till openpyxl 1.8.x, styles are mutable. Their attribute can be assigned directly like this:

from openpyxl.workbook import Workbook
from openpyxl.style import Color

wb = Workbook()
ws = wb.active
ws['A1'].style.font.color.index = Color.RED

However from of openpyxl 1.9, styles are immutable.

Styles are shared between objects and once they have been assigned they cannot be changed. This stops unwanted side-effects such as changing the style for lots of cells when instead of only one.

To create a new style object, you can assign it directly, or copy one from an existing cell's style with new attributes, answer to the question as an example(forgive my Chinese English):

from openpyxl.styles import colors
from openpyxl.styles import Font, Color
from openpyxl import Workbook
wb = Workbook()
ws = wb.active

a1 = ws['A1']
d4 = ws['D4']

# create a new style with required attributes
ft_red = Font(color=colors.RED) 
a1.font = ft_red

# you can also do it with function copy
ft_red_bold = ft_red.copy(bold=True)

# you can copy from a cell's style with required attributes
ft_red_sigle_underline = a1.font.copy(underline="single")

d4.font = ft_red_bold

# apply style to column E
col_e = ws.column_dimensions['E']
col_e.font = ft_red_sigle_underline

A cell' style contains these attributes: font, fill, border, alignment, protection and number_format. Check openpyxl.styles.

They are similar and should be created as an object, except number_format, its value is string type.

Some pre-defined number formats are available, number formats can also be defined in string type. Check openpyxl.styles.numbers.

from openpyxl.styles import numbers

# use pre-defined values
ws.cell['T49'].number_format = numbers.FORMAT_GENERAL
ws.cell(row=2, column=4).number_format = numbers.FORMAT_DATE_XLSX15

# use strings
ws.cell['T57'].number_format = 'General'
ws.cell(row=3, column=5).number_format = 'd-mmm-yy'
ws.cell['E5'].number_format = '0.00'
ws.cell['E50'].number_format = '0.00%'
ws.cell['E100'].number_format = '_ * #,##0_ ;_ * -#,##0_ ;_ * "-"??_ ;_ @_ '
不忘初心 2024-12-27 08:15:47

从 openpyxl-1.7.0 开始,您也可以这样做:

cell.style.fill.start_color.index = "FF124191"

我有几个辅助函数,可以在给定的单元格上设置样式 - 例如页眉、页脚等。

As of openpyxl-1.7.0 you can do this too:

cell.style.fill.start_color.index = "FF124191"

I've got a couple of helper functions which set a style on a given cell - things like headers, footers etc.

东北女汉子 2024-12-27 08:15:47

这对我有用(字体颜色+粗体):

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

wb = Workbook()
ws = wb['SheetName']

ws.cell(row_number,column_number).font = Font(color = "0000FF",bold = True)

This worked for me (font colour + bold font):

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

wb = Workbook()
ws = wb['SheetName']

ws.cell(row_number,column_number).font = Font(color = "0000FF",bold = True)
随心而道 2024-12-27 08:15:47

您可以定义通用样式,然后将其应用到任何单元格或范围。

定义样式:

定义样式:

应用于单元格。
输入图片此处描述

You can define a common style then you can apply the same to any cell or range.

Define Style:

Define Style:

Apply on a cell.
enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文