Read an excel file with Python and modify it without changing the style

Viewed 1813

I have a excel file which has specific format, font and color etc. I would like to read it using Python libraries like pandas (pd.read_excel) and just modify a few cells without affecting the style. Is it possible? Currently, when I read and write using pandas, the style changes and it seems difficult to make the complex style in Python again.

Is there a way to load and store the format/style of Excel file when we are reading it, to be applied when it is being saved? I just want to modify the value of few cells.

2 Answers

You can use the openpyxl library like this:

from openpyxl import Workbook, load_workbook

workbook = load_workbook("test.xlsx") # Your Excel file
worksheet = workbook.active # gets first sheet

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

workbook.save("test.xlsx")
Related