[英]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.我正在使用 openpyxl 3.0.7 版努力解决以下问题 我想将一个单元格的样式复制到另一个单元格。 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
.我最初的想法基本上是做
sheet["E1"].font = sheet["D1"].font
。
That bit shoots out TypeError: unhashable type: 'StyleProxy'
.那位射出
TypeError: unhashable type: 'StyleProxy'
。 Using just .style
doesn't really do all that much so it's not suitable.只使用
.style
并不能真正做到那么多,所以它不合适。
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.