I am trying to find a library that overwrites an existing cell to change its contents using Python.
what I want to do:
- read from .xlsx file
- compare cell data determine if change is needed.
- change data in cell Eg. overwrite date in cell 'O2'
- save file.
I have tried the following libraries:
- xlsxwriter
- 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?
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()
Alternatively you can use xlwing, which (if I had to guess) seems to be using this approach under the hood.
>>> import xlwings as xw
>>> wb = xw.Book() # this will create a new workbook
>>> wb = xw.Book('FileName.xlsx') # connect to an existing file in the current working directory
>>> wb = xw.Book(r'C:\path\to\file.xlsx') # on Windows: use raw strings to escape backslashes
来源:https://stackoverflow.com/questions/28484349/overwriting-existing-cells-in-an-xlsx-file-using-python