Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to an existing excel file without breaking formulas with openpyxl?

When you write to an excel file from Python in the following manner:

import pandas
from openpyxl import load_workbook

book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx') 
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()

Formulas and links to charts which are in the existing sheets, will be saved as values.

How to overwrite this behaviour in order to preserve formulas and links to charts?

like image 852
BP_ Avatar asked Nov 28 '13 09:11

BP_


People also ask

How do you write to an existing Excel file without overwriting data using Python?

How to write to an existing Excel file without overwriting data using Python Pandas? To write to an existing Excel file without overwriting data using Python Pandas, we can use ExcelWriter . to create the ExcelWriter instance with the Excel file path. And then we call save to save the changes.


1 Answers

Openpyxl 1.7 contains several improvements for handling formulae so that they are preserved when reading. Use guess_types=False to prevent openpyxl from trying to guess the type for a cell and 1.8 includes the data_only=True option if you want the values but not the formula.

Want to preserve charts in the 2.x series.

like image 114
Charlie Clark Avatar answered Sep 19 '22 12:09

Charlie Clark