简体   繁体   English

将pd数据框填入现有Excel工作表(使用openpyxl v2.3.2)

[英]Fill in pd data frame into existing excel sheet (using openpyxl v2.3.2)

I want to fill in some pandas data frames into an existing excel file. 我想将一些pandas数据帧填入现有的 excel文件中。 I followed the instructions in: How to write to an existing excel file without overwriting data (using pandas)? 我按照以下说明操作: 如何写入现有的excel文件而不覆盖数据(使用pandas)? using: 使用:

  from openpyxl import load_workbook
  import pandas as pd
  import numpy as np

  book=load_workbook("excel_proc.xlsx")
  writer=pd.ExcelWriter("excel_proc.xlsx", engine="openpyxl")
  writer.book = book
  writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
  data_df.to_excel(writer, sheet_name="example", startrow=100, startcol=5, index=False)
  writer.save()

However, the existing sheets will be deleted, the "example" sheet is generated and only the df is integrated at the defined location. 但是,将删除现有工作表,生成“示例”工作表,并且仅在定义的位置集成df。 What did I do wrong? 我做错了什么? I want the "data_df" written into the existing excel file in the existing "example" sheet, keeping the other sheets and data. 我希望将“data_df”写入现有“示例”表中的现有excel文件中,保留其他表和数据。

Thanks 谢谢

Example df: 示例df:

data_df=pd.DataFrame(np.arange(12).reshape((2, 6)), index=["Time","Value"])

I resolved the problem on my own. 我自己解决了这个问题。 I realised that even load_workbook cannot load my file. 我意识到即使load_workbook也无法加载我的文件。 Therefore, I updated the openpyxl package (conda install openpyxl). 因此,我更新了openpyxl包 (conda install openpyxl)。 The version not working was : v2.3.2 (python 35). 不起作用的版本是:v2.3.2 (python 35)。 The version now working is: v2.4.0. 现在运行版本是:v2.4.0。

I do not really know, if it was the reason at the end. 我真的不知道,如果这是最后的原因。 But now the excels are filled in the defined locations and the data is kept. 但是现在excels被填充在定义的位置并且数据被保留。

You might be interested in learning xlwings , which makes it a lot easier to work with excel files from python. 您可能对学习xlwings感兴趣,这使得使用python中的excel文件变得更加容易。

In any case I would start by reading the existing data in the sheet, combine the data as you wish in python, and finally overwrite the sheet. 在任何情况下,我都会先阅读工作表中的现有数据,在python中按照您的意愿组合数据,最后覆盖工作表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM