简体   繁体   English

Python Excel 将单元格样式从一个复制到另一个openpyxl

[英]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.

相关问题 openpyxl - 我无法将单元格样式复制到另一个中 - openpyxl - I can't copy the cell style in another one Python Excel(xlrd,xlwt) - 如何从一个单元格复制样式并将其放在另一个单元格上 - Python Excel (xlrd, xlwt) - How to copy a style from one cell and put it on another 使用openpyxl将公式从一个单元格复制到另一个单元格 - Copy formula from one cell to another using openpyxl 使用openpyxl将单元格值列从一个工作簿复制到另一个工作簿 - Copy column of cell values from one workbook to another with openpyxl 复制单元格样式openpyxl - copy cell style openpyxl 使用 Python 和 openpyxl 将 1 个特定行从一个 Excel 电子表格复制到另一个 - Using Python & openpyxl to copy 1 specific row from one excel spreadsheet to another 如何使用 openpyxl 库将列从一张 excel 表复制到另一张 python? - How can I copy columns from one excel sheet to another with python using openpyxl Library? 如何在openpyxl中将图像从一个Excel复制到另一个? - How to copy image from one excel to another in openpyxl? 有什么方法可以使用openpyxl python从excel文件中读取单元格内每个单词的样式 - Is there any way to while reading from excel file get style of each word inside cell using openpyxl python 使用 openpyxl 将工作表(数据+样式)从工作簿复制到 Python 中的另一个 - Copy a worksheet (data+style) from a workbook to another in Python using openpyxl
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM