Reputation: 288
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.
Upvotes: 2
Views: 3612
Reputation: 288
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.
Upvotes: 3