openpyxl 覆盖所有数据而不是更新 excel sheet

openpyxl overwrites all data instead of update the excel sheet

我正在尝试从文本文件中读取字符串并将其写入 excel sheet 而不覆盖。我在某处发现要更新 excel sheets,使用了 openpyxl。但是我的脚本只是覆盖了整个 sheet。我希望其他数据也一样。

python 脚本:

from openpyxl import Workbook     
file_name="D:\a.txt"    
content={}    
with open(file_name) as f:
    for line in f:
        (key,value)=line.split(":")
        content[key]=value

wb=Workbook()
ws=wb.active
    r = 2
for item in content:
    ws.cell(row=r, column=3).value = item
    ws.cell(row=r, column=4).value = content[item]
    r += 1
    
wb.save("D:\Reports.xlsx")

Excel sheet 脚本前:

Excel sheet 在脚本之后:

如何将数据写入 excel 并覆盖其他内容?帮助。

覆盖是由于使用 wb.save() 和您的硬编码起始行号 r = 2.
保存文件 1) 如果你不关心每次执行脚本时覆盖行,你可以使用这样的东西:

from openpyxl import Workbook
from openpyxl import load_workbook

path = 'P:\Desktop\'
file_name = "input.txt"    
content= {}    
with open(path + file_name) as f:
    for line in f:
        (key,value)=line.split(":")
        content[key]=value

wb = load_workbook(path + 'Reports.xlsx')
ws = wb.active

r = 2
for item in content:
    ws.cell(row=r, column=3).value = item
    ws.cell(row=r, column=4).value = content[item]
    r += 1

wb.save(path + "Reports.xlsx")

2) 如果您关心覆盖行和列号(3 和 4),您可以尝试这样的操作:

from openpyxl import Workbook
from openpyxl import load_workbook

path = 'P:\Desktop\'
file_name = "input.txt"    
content= []    
with open(path + file_name) as f:
    for line in f:
        key, value = line.split(":")
        content.append(['','', key, value]) # adding empty cells in col 1 + 2

wb = load_workbook(path + 'Reports.xlsx')
ws = wb.active

for row in content:
    ws.append(row)

wb.save(path + "Reports.xlsx")