简体   繁体   中英

openpyxl - I can't copy the cell style in another one

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?

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)

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