[Python] How to create a copy of an Excel file with rich text using Python

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am looking for a method to copy Excel data from an other file. I have a 'file_1.xlsx', and I would like to create a 'file_1_copy.xlsx' that does not exist. The copy has to be exactly the same that the original file.

    Is there some method in Python to copy an Excel file completely?

    I tried to write code that does this manually:

    import openpyxl
    from openpyxl.styles import Font

    wb = openpyxl.load_workbook('test excel.xlsx')
    ws = wb.active

    new_wb = openpyxl.Workbook()
    new_ws = new_wb.active

    for row in ws.iter_rows():
    for cell in row:
    new_cell = new_ws.cell(row=cell.row, column=cell.col_idx, value=cell.value)
    if cell.has_style:
    new_cell.font = Font(name=cell.font.name, size=cell.font.size, bold=cell.font.bold, italic=cell.font.italic, color=cell.font.color)

    new_wb.save('test copie excel.xlsx')


    [​IMG]

    In the image above, on the left is the original file. On the right, the copy.

    The issue is that the text in the first cell of the copy is supposed to be in 2 colors: red and blue, and highlighted in yellow. In the copy, I got only one color, all the text became red, and is not highlighted anymore.

    Continue reading...

Compartilhe esta Página