简体   繁体   中英

Python Excel copy cell style from one to another openpyxl

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.

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. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM