Overwriting existing cells in an XLSX file using Python

做~自己de王妃 提交于 2019-12-01 23:21:35
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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!