![](/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.