简体   繁体   中英

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. I followed the instructions in: How to write to an existing excel file without overwriting data (using 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. 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.

Thanks

Example 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. Therefore, I updated the openpyxl package (conda install openpyxl). The version not working was : v2.3.2 (python 35). The version now working is: 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.

You might be interested in learning xlwings , which makes it a lot easier to work with excel files from python.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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