簡體   English   中英

使用Python覆蓋XLSX文件中的現有單元格

[英]Overwriting existing cells in an XLSX file using Python

我正在嘗試找到一個庫,該庫將覆蓋現有單元以使用Python更改其內容。

我想做的事:

  1. 從.xlsx文件讀取
  2. 比較單元格數據以確定是否需要更改。
  3. 更改單元格Eg中的數據。 覆蓋單元格“ O2”中的日期
  4. 保存存檔。

我已經嘗試了以下庫:

    • xlsxwriter
  1. 的組合:
    • xlrd
    • xlwt
    • xlutils
    • openpyxl

xlsxwriter僅寫入新的Excel工作表和文件。 組合:可以從.xlsx讀取,但只能寫入.xls openpyxl:從現有文件讀取,但不寫入現有單元格只能創建新的行和單元格,或者可以創建整個新工作簿

任何建議將不勝感激。 其他圖書館? 如何操縱上面的庫來覆蓋現有文件中的數據?

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

或者,您可以使用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