Python Excel copy cell style from one to another openpyxl
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.
Copying styles from a range to another range?
Your workload are to copy the six styles, e.g.
new_third_col_cell.font = copy(third_col_cell.font)
Try to copy only the style reference, instead of assigning new styles, for instance
target_cell._style = copy(source_cell._style)
You can save ~10 %, per Style, if not all Styles are are used in all cells.
Copy only used styles, for instance:
if source_cell._style.fontId: target_cell.font = copy(s_cell.font)
...
Besides this, consider to slim your code, for instance:
def copy_style(s_cell, t_cell):
...
def merge_cells(ws, row, offset, columns_456):
...
def main(recommended, plans):
column_456 = [4,5,6]
for a in xrange(1, len(plans)):
offset = 3 * a
# Create blank templates for plans
for x in xrange(5, 549):
if x != 42:
for column in column_456:
cell = recommended.cell(row=x, column=column)
if cell.has_style:
copy_style(cell, recommended.cell(row=x, column=column+offset))
if (x >= 6 and x <= 33) or x == 36 or x == 41 or x == 44:
merge_cells(recommended, x, offset, column_456)
Related Topics
What's a Good Equivalent to Subprocess.Check_Call That Returns the Contents of Stdout
Best Way to Determine If a Sequence Is in Another Sequence
Installing Module from Github Through Jupyter Notebook
Sending Mail from Python Using Smtp
How to Use Multiple Requests and Pass Items in Between Them in Scrapy Python
"Ssl: Certificate_Verify_Failed" Error When Scraping Https://Www.Thenewboston.Com/
Matrix Multiplication in Pure Python
Removing Entries from a Dictionary Based on Values
How to Use Append with Pickle in Python
Downloading a Directory Tree with Ftplib
How to Rotate a Matplotlib Plot Through 90 Degrees
How to Highlight Specific X-Value Ranges
How to Find Unused Functions in Python Code
How to Replace Django's Primary Key with a Different Integer That Is Unique for That Table
[] and {} VS List() and Dict(), Which Is Better
Django What Is Reverse Relationship