【问题标题】:Is there a way to create a NamedStyle from a cell in python?有没有办法从 python 中的单元格创建 NamedStyle?
【发布时间】:2023-02-10 15:14:18
【问题描述】:

这似乎是一个基本问题,但我在互联网上找不到任何东西。

我想在 python 中基于 excel 中的单元格创建样式模板/NamedStyle。 我想基本上复制一个单元格的所有格式样式并存储它,然后根据需要使用它。

例子 :

A=NamedStyle(name="OFF")     #Creating a NamedStyle

后来,是这样的:

A=NamedStyle(cell_obj.style)  #Importing the style of an existing cell into the NamedStyle

再后来,

cell_obj.style=A             #Applying NamedStyle to a cell

我收到一个"TypeError: 'Cell' object does not support item assignment" for A=NamedStyle(cell_obj.style)

我知道这种语法可能是错误的,但是正确的语法是什么?我在互联网上所能找到的就是创建 NamedStyle 并亲自编辑属性然后使用它。 我想基本上将 excel 的现有单元格的样式导入 NamedStyle,以便我可以在将来的某个时间点在不同的 excel 中重用它。我该怎么做呢?

问候,
维韦克

【问题讨论】:

    标签: python excel formatting openpyxl


    【解决方案1】:

    你想做这样的事情吗?
    单元格 B2 应用了样式、字体、边框、对齐方式、填充、日期格式。这些被复制到称为“namedstyle”的样式中。
    原始值输入到单元格“B4”中并应用“namedstyle”。

    from openpyxl import load_workbook
    from openpyxl.styles import NamedStyle, 
    from copy import copy
    
    
    wb = load_workbook("data.xlsx")
    ws = wb['Sheet4']
    
    ### Select cell to copy from
    style_cell = ws['B2']
    
    ### Create Named Style
    namedstyle = NamedStyle(name="namedstyle")
    
    ### Copy Syles
    namedstyle.font = copy(style_cell.font)
    namedstyle.alignment = copy(style_cell.alignment)
    namedstyle.border = copy(style_cell.border)
    namedstyle.fill = copy(style_cell.fill)
    namedstyle.alignment = copy(style_cell.alignment)
    
    namedstyle.number_format = style_cell.number_format
    
    ### Register style with the workbook:
    wb.add_named_style(namedstyle)
    
    ### But named styles will also be registered automatically the first time they are assigned to a cell:
    ws['B4'].value = 36194
    ws['B4'].style = namedstyle
    
    wb.save("data1.xlsx")
    

    【讨论】:

      猜你喜欢
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多