1

I am struggling with the following using openpyxl version 3.0.7 I want to copy the style of one cell to another. That means, background colour, font, etc. However, I don't know how I can do that.

My initial idea was basically to do sheet["E1"].font = sheet["D1"].font.

That bit shoots out TypeError: unhashable type: 'StyleProxy'. Using just .style doesn't really do all that much so it's not suitable.

I found a few solutions online like the one from here. However, I don't know how I can apply it to my specific needs seeing as I struggle to even transfer the font from one cell to another.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Squary94
  • 248
  • 2
  • 16
  • 1
    I'd suggest taking the solution out of the edited question and making your own answer, then accepting it, so the question shows up in searches as answered. – sj95126 Oct 06 '21 at 14:35

1 Answers1

2

Shortly after typing this out, I found the solution.

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)

The only thing left to do would be to do this in a loop. That would be achievable by doing something like

for i in range(....): 
    sheet["E" + str(i)].font= copy(sheet["D" +str(i)].font) 
    etc. 
Dharman
  • 30,962
  • 25
  • 85
  • 135
Squary94
  • 248
  • 2
  • 16