pythonexcelopenpyxlxlwings

Clear Content of Excel Using Python


I would like to clear the content of the Excel file using Python and re-write it at the end with different values. I would like to do it while Excel remains open and don't want to close before re-writing it again.

import pandas as pd

Tab = pd.read_excel("abc.xls",sheet_name="Sheet1")
Col_A = Tab['Col A']

The Col_A in excel has the following values currently. I would like to clear those values except the heading 'Col A' and update them with new values.

Old Values
100
200
300
400
500
New Values
600
700
800
900
1000

I would like to keep excel open and save the file after updating new values in Col A.


Solution

  • This is an example using Xlwings;

    The sheet contains the values 100 to 500 in cells A1 to A5 in 100 increments.
    The workbook is opened in Excel with this pre-populated Sheet displayed.
    Python then waits for a key stroke to continue.
    When a key is pressed these cells are updated with the values 600 to 1000 down the column overwriting the existing values in real time. Then waits for key stroke again.
    When a key is pressed the Excel file is saved and Excel exits.

    import xlwings as xw
    
    
    with xw.App(visible=True) as app:
        wb = xw.Book('foo.xlsx')
        ws = wb.sheets["Sheet1"]
    
        input("Press any key to update values")
    
        ws['A1'].value = [[600], [700], [800], [900], [1000]]
    
        input("Press any key to Save file and exit")
    
        wb.save('foo.xlsx')