I am working on an xlsx with two sheets: the first one containing raw data and the second one containing a pivot table. I cannot manage to modify the data-sheet without getting the pivot one in plain text: I've seen many people have the same issue but I couldn't find a working solution.
I am working with version 2.6.2 of openpyxl which according to the documentation (https://openpyxl.readthedocs.io/en/stable/pivot.html) should preserve pivot table.
Below my code which works without preserving the pivot.
sheet_name='Data'
book = load_workbook(local_path + 'file_name'+ '.xlsx')
wrs = book["my_pivot_table"]
pivot = wrs ._pivots[0]
pivot.cache.refreshOnLoad = True
writer = pd.ExcelWriter(local_path + 'file_name'+ '.xlsx', engine='openpyxl')
sh = book[sheet_name]
sh.delete_cols(1, 20)
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df_tb_exp.to_excel(writer, sheet_name=sheet_name, index=False)
writer.save()
Thanks
UPDATE
I tried without using Pandas for reading and writing the xlsx but unfortunately still have the pivot table in plain text - moreover this code empties the Data sheet but it doesn't fill it with the new data, I am probably missing smtg...
sheet_name='Data'
book = load_workbook(local_path + 'file_name'+ '.xlsx')
ws = book["my_pivot_table"]
pivot = ws._pivots[0]
pivot.cache.refreshOnLoad = True
sh = book[sheet_name]
sh.delete_cols(1, 20)
for r in dataframe_to_rows(df_tb_exp, index=False, header=True):
sh.append(r)
book.save(local_path + 'file_name'+ '.xlsx')
Thanks!