1

I need to copy a cell to another one with all the styles associated, including the width dimension.

below a simple example (an instruction doesn't work):

import openpyxl
from copy import copy

src_wb = openpyxl.load_workbook("C:\\Users\\Admin\\Desktop\\database.xlsx")
src_ws = src_wb[src_wb.sheetnames[0]]

dst_wb = openpyxl.Workbook()
dst_ws = dst_wb.active
dst_ws.title = "TEST"

src_cell = src_ws.cell(row=1, column=1)
dst_cell = dst_ws.cell(row=1, column=1)

if src_cell.has_style:
    dst_cell._style = copy(src_cell._style) # it doesn't work..

dst_cell.value = src_cell.value

dst_wb.save("test.xlsx")
dst_wb.close()

how can I fix the issue?

TurboC
  • 777
  • 1
  • 5
  • 19
  • Does this answer your question? [Setting styles in Openpyxl](https://stackoverflow.com/questions/8440284/setting-styles-in-openpyxl) – michaeldel Jun 07 '20 at 03:15
  • See [here](https://stackoverflow.com/questions/61892135/how-to-copy-cell-from-one-workbook-to-an-other-workbook-with-its-set-style/61931962#61931962) for a complete answer and explenation as to why copying `cell._style` doesn't work. – Dror Av. Jun 07 '20 at 14:55

1 Answers1

0

Try this

if cell.has_style:
    new_cell.font = copy(cell.font)
    new_cell.border = copy(cell.border)
    new_cell.fill = copy(cell.fill)
    new_cell.number_format = copy(cell.number_format)
    new_cell.protection = copy(cell.protection)
    new_cell.alignment = copy(cell.alignment)
  • yeah, it works but, isn't there a way to do it in a single instruction? and what about the width dimension? – TurboC Jun 07 '20 at 06:39
  • please read the documentation https://openpyxl.readthedocs.io/en/stable/styles.html , it will help you. – Ryhan Ahmed Jun 07 '20 at 11:19