简体   繁体   English

使用Python覆盖XLSX文件中的现有单元格

[英]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. 我正在尝试找到一个库,该库将覆盖现有单元以使用Python更改其内容。

what I want to do: 我想做的事:

  1. read from .xlsx file 从.xlsx文件读取
  2. compare cell data determine if change is needed. 比较单元格数据以确定是否需要更改。
  3. change data in cell Eg. 更改单元格Eg中的数据。 overwrite date in cell 'O2' 覆盖单元格“ O2”中的日期
  4. save file. 保存存档。

I have tried the following libraries: 我已经尝试了以下库:

    • xlsxwriter xlsxwriter
  1. combination of: 的组合:
    • xlrd xlrd
    • xlwt xlwt
    • xlutils xlutils
    • openpyxl openpyxl

xlsxwriter only writes to a new excel sheet and file. xlsxwriter仅写入新的Excel工作表和文件。 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 组合:可以从.xlsx读取,但只能写入.xls openpyxl:从现有文件读取,但不写入现有单元格只能创建新的行和单元格,或者可以创建整个新工作簿

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. 或者,您可以使用xlwing ,(如果我不得不猜测的话)似乎在后台使用了这种方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM