Copy excel sheet with style in another already-created file with Python

Viewed 50

I have a Python code that, at the end of the process, it creates an Excel file with several worksheets, what I'm trying to do is copy a sheer from another file that is read with its exact format (cells with background color, different fonts and letter sizes, etc) and paste it as it is in the main file without affecting the other previously-created sheets, the method that I'm currently using doesn't allow me to do that because it overwrites the new file over the previously-created one. Does someone have a suggestion or way of doing this?

The method I'm currently using, which is obtained from: Read an excel file with Python and modify it without changing the style:

from openpyxl import Workbook, load_workbook

workbook2 = load_workbook("readme tab.xlsx") # Your Excel file
worksheet2 = workbook2.active # gets first sheet

for row in range(1, 10):
    # Writes a new value PRESERVING cell styles.
    worksheet2.cell(row=row, column=1, value=f'NEW VALUE {row}')

workbook2.save(path)

Reference of the code I'm using, in order:

import xlsxwriter
import pandas as pd

path = r"Archivo.xlsx"

writer = pd.ExcelWriter(path)

df1.to_excel(writer, sheet_name='Data')

workbook = writer.book
worksheet = writer.sheets['Data']
ws = workbook.add_worksheet('Graph')

worksheet.set_column(1, 29, 30)

writer.save()

from openpyxl import Workbook, load_workbook

workbook2 = load_workbook("readme tab.xlsx") # Your Excel file
worksheet2 = workbook2.active # gets first sheet

for row in range(1, 10):
    # Writes a new value PRESERVING cell styles.
    worksheet2.cell(row=row, column=1, value=f'NEW VALUE {row}')

workbook2.save(path)
1 Answers

You can copy a sheet (including its format style) with the method add_sheet.
And assuming that workbook is the workbook to which you're adding the sheet :

Replace :

workbook2 = load_workbook("readme tab.xlsx") # Your Excel file
worksheet2 = workbook2.active # gets first sheet

for row in range(1, 10):
    # Writes a new value PRESERVING cell styles.
    worksheet2.cell(row=row, column=1, value=f'NEW VALUE {row}')

workbook2.save(path)
By :
ws2 = load_workbook('readme tab.xlsx').active
ws2._parent = workbook
workbook._add_sheet(ws2)
workbook.save(path)
Related