![](/img/trans.png)
[英]Write to an existing xlsx file, overwriting just some sheets in Python
[英]Overwriting existing cells in an XLSX file using Python
我正在嘗試找到一個庫,該庫將覆蓋現有單元以使用Python更改其內容。
我想做的事:
我已經嘗試了以下庫:
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.