简体   繁体   中英

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

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)

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)

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