Home » excel » python – Preserve original cell formatting in openpyxl

python – Preserve original cell formatting in openpyxl

Posted by: admin March 9, 2020 Leave a comment


I am using openpyxl version 2.3.5 to write data into an existing, formatted, excel template (with .xlsx extension). The problem is that when I write to a cell, the formatting of that cell is completely overwritten. For example, Cell A1 has a blue fill. When I execute the following code:

wb = xl.load_workbook('Template.xlsx')
ws = wb.worksheets[0]
ws['A1'] = "TEST"

The fill of cell A1 is lost. There is a lot of formatting in the spreadsheet, so I do not want to manually specify all of it. I have tried copying the original formatting of the cell from itself to no avail. This code did not work:

ws['A1'].style = ws['A1'].style

Is there any way to keep and/or copy the original style/formatting of the excel spreadsheet, and only write in the data?

How to&Answers:

Well, openpyxl don’t have a good solution for this issue yet. However, you can use pywin32 to directly interact with Windows API. You can do everything you want there.