问题描述
我正在处理具有两张纸的xlsx:第一张纸包含原始数据,第二张纸包含数据透视表。在没有用明文表达数据透视表的情况下,我无法设法修改数据表:我已经看到很多人都遇到了同样的问题,但是我找不到可行的解决方案。
我正在使用openpyxl的2.6.2版本,根据文档(https://openpyxl.readthedocs.io/en/stable/pivot.html),该版本应保留数据透视表。
下面的代码在不保留数据透视的情况下起作用。
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()
谢谢
更新
我尝试不使用Pandas来读取和写入xlsx,但不幸的是,数据透视表仍然以纯文本格式显示-而且此代码清空了数据表,但没有用新数据填充它,我可能会丢失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')
谢谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)