简体   繁体   中英

Python - save new Excel sheet with existing format

I want to save excel sheet with existing sheet formats and background color.

I could save successfully to a new file with out old file format.

How can I keep the existing excel sheet format when save in to a new file.

writer = pd.ExcelWriter('New.xlsx', engine='xlsxwriter')
dfDiff.to_excel(writer, sheet_name='DIFF', index=False)
writer.save()

I had no good experience with pandas and format styles... what works if you use win32com like this example:

from win32com.client import DispatchEx
excel = DispatchEx('Excel.Application')
wbP=excel.Workbooks.Open(r'C:\Temp\Junk\Temp.xlsx')
wbG=excel.Workbooks.Open(r'C:\Temp\Junk\Temp2.xlsx')
wbG.Worksheets('TAA2').Copy(Before=wbP.Worksheets("TAA"))
wbP.SaveAs(r'C:\Temp\Junk\Temp.xlsx')
excel.Quit()
del excel # ensure Excel process ends

this copies everything... (styles, formats, formulas etc.)

Another option is copy the whole workbook and delete the not needed sheets, if you create a new file and not editing an existing one... Copy worksheet from one workbook to another one using Openpyxl

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