Search code examples
pythonexcelread-write

Overwriting existing cells in an XLSX file using Python


I am trying to find a library that overwrites an existing cell to change its contents using Python.

what I want to do:

  1. read from .xlsx file
  2. compare cell data determine if change is needed.
  3. change data in cell Eg. overwrite date in cell 'O2'
  4. save file.

I have tried the following libraries:

    • xlsxwriter
  1. combination of:
    • xlrd
    • xlwt
    • xlutils
    • openpyxl

xlsxwriter only writes to a new excel sheet and file. combination: works to read from .xlsx but only writes to .xls openpyxl: reads from existing file but doesn't write to existing cells can only create new rows and cells, or can create entire new workbook

Any suggestions would greatly be appreciated. Other libraries? how to manipulate the libraries above to overwrite data in an existing file?


Solution

  • from win32com.client import Dispatch
    import os
    
    xl = Dispatch("Excel.Application")
    xl.Visible = True # otherwise excel is hidden
    
    # newest excel does not accept forward slash in path
    wbs_path = r'C:\path\to\a\bunch\of\workbooks'
    
    for wbname in os.listdir(wbs_path):
        if not wbname.endswith(".xlsx"):
            continue
        wb = xl.Workbooks.Open(wbs_path + '\\' + wbname)
        sh = wb.Worksheets("name of sheet")
        sh.Range("A1").Value = "some new value"
        wb.Save()
        wb.Close()
    xl.Quit()