Search code examples
excelpandaspandas.excelwriter

how to update a portion of existing excel sheet with filtered dataframe?


I have an excel workbook with several sheets. I need to read a portion from one of the sheets, get a filtered dataframe and write a single value from that filtered dataframe to a specific cell in the same sheet. What is the best way to accomplish this, ideally without opening the excel workbook? I need to run this on linux, so can't use xlwings. I don't want to write the entire sheet, but just a selected cell/offset inside it. I tried the following to write to the existing sheet, but doesn't seem to work for me (no update occurs at the desired cell):

with pd.ExcelWriter('test.xlsx', engine='openpyxl') as writer:
    writer.book = load_workbook('test.xlsx')
    df_filtered.to_excel(writer, 'Sheet_Name', columns=['CS'], startrow=638, startcol=96)

Any tips would be helpful. Thanks.


Solution

  • If you're just writing a single cell the below should suffice.

    import pandas as pd
    import openpyxl
    
    df = pd.DataFrame(data=[1,2,3], columns=['col'])
    filtered_dataframe = df[df.col == 1].values[0][0]
    
    filename = 'test.xlsx'
    wb = openpyxl.load_workbook(filename)
    wb['Sheet1'].cell(column=1, row=2, value=filtered_dataframe)
    wb.save(filename)
    

    I believe your issue was that you never called the save method of the writer.