【问题标题】:Python Excel copy cell style from one to another openpyxlPython Excel将单元格样式从一个复制到另一个openpyxl
【发布时间】:2021-11-26 08:52:02
【问题描述】:

我正在使用 openpyxl 版本 3.0.7 解决以下问题 我想将一个单元格的样式复制到另一个单元格。这意味着,背景颜色,字体等。 但是,我不知道该怎么做。

我最初的想法基本上是做 sheet["E1"].font = sheet["D1"].font.

那个位射出TypeError: unhashable type: 'StyleProxy'。 仅使用 .style 并不能真正发挥作用,因此不适合。

我在网上找到了一些解决方案,例如the one from here。但是,我不知道如何将它应用于我的特定需求,因为我什至很难将字体从一个单元格转移到另一个单元格。

【问题讨论】:

  • 我建议从已编辑的问题中取出解决方案并做出自己的答案,然后接受它,这样问题就会在搜索中显示为已回答。

标签: python excel formatting openpyxl


【解决方案1】:

在输入此内容后不久,我找到了解决方案。

from copy import copy
wb = openpyxl.load_workbook('C:\\path...\\')
sheet = wb["Name of the worksheet"]

sheet["E1"].font = copy(sheet["D1"].font)
sheet["E1"].border = copy(sheet["D1"].border)
sheet["E1"].fill = copy(sheet["D1"].fill)
sheet["E1"].number_format = copy(sheet["D1"].number_format)
sheet["E1"].protection = copy(sheet["D1"].protection)
sheet["E1"].alignment = copy(sheet["D1"].alignment)

剩下要做的就是循环执行此操作。这可以通过做类似的事情来实现

for i in range(....): 
    sheet["E" + str(i)].font= copy(sheet["D" +str(i)].font) 
    etc. 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2022-09-23
    • 1970-01-01
    • 2020-03-30
    • 2014-06-13
    • 2018-03-15
    相关资源
    最近更新 更多