Overwriting existing cells in an XLSX file using Python

旧街凉风 提交于 2019-12-31 02:58:10

问题


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?


回答1:


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()



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!