将Excel中定义的自定义样式与openxyl一起使用

时间:2019-03-04 07:08:21

标签: python excel openpyxl

通过 openpyxl ,您可以使用在Excel中定义的built-in styles,如下所示:

wb = load_workbook("My_Template.xlsx")
ws = wb["My_super_Worksheet"]

ws["B2"].value = '=Hyperlink("https://stackoverflow.com", "SO")'
ws["B2"].style = "Hyperlink"

但是,您将如何使用Excel文件中定义的自定义样式?可能看起来像这样:

wb = load_workbook("My_Template.xlsx")
ws = wb["My_super_Worksheet"]

wb.register_style("My_Custome_style")  # defined as custom style in My_Template.xlsx

ws["B2"].value = '=Hyperlink("https://stackoverflow.com", "SO")'
ws["B2"].style = ""My_Custome_style""

我发现的唯一方法是将程序中的样式重新定义为Named Styles并保存,但这将涉及到再次定义样式,而不是重新使用已经存在的样式。

非常感谢。

1 个答案:

答案 0 :(得分:0)

有一种解决方法不能解决问题,但可以帮助解决问题。

  1. 在某些给定的单元格中设置格式(例如,在名为“ STYLES”的工作表中)
  2. 检索所有样式并将其注册到openpyxl
  3. 使用样式及其名称

Excel 中,将显示以下内容:

Styles defined in STYLES

Python 中,您可以添加以下函数并调用它:

from copy import copy
import logging
from openpyxl.styles import NamedStyle
from openpyxl.workbook import Workbook
from openpyxl.worksheet.worksheet import Worksheet
from typing import Dict

def _register_styles(wb:Workbook, ws_style: Worksheet) -> Dict[str, NamedStyle]:
    """Parse a column of cells and register the styles
    (the style names are the values of cells)

    Args:
        wb: The workbook
        ws_style: The worksheet with the styles defined

    Returns:
        Dictionary of styles, by names
    """
    list_styles = dict()  # type: Dict[str, NamedStyle]
    # Register styles of a config cells
    col, row = "A", 2
    cell = ws_style[col + str(row)]  # or in Python 3.6+: f"{col}{row}"
    while cell.value:
        style = NamedStyle(name=cell.value)
        style.font = copy(cell.font)
        style.fill = copy(cell.fill)
        style.border = copy(cell.border)
        style.alignment = copy(cell.alignment)
        style.number_format = copy(cell.number_format)

        try:
            wb.add_named_style(style)
        except ValueError as e:
            logging.warning("W006: style creation skipped because {}".format(e))
        list_styles[cell.value] = style

        row += 1
        cell = ws_style[col + str(row)]  # or in Python 3.6+: f"{col}{row}"

    return list_styles


wb = load_workbook("My_Template.xlsx")
_register_styles(wb, wb["STYLES"])

注意:如果您使用3.4之前的Python,只需删除函数原型开始处的类型提示即可: def _register_styles(wb, ws_style):