openpyxl会覆盖所有数据,而不是更新excel表

时间:2016-09-20 09:14:21

标签: python excel openpyxl

我正在尝试从文本文件中读取字符串并将其写入excel表而不会覆盖。我找到了更新excel表单的地方,openpyxl在使用中。但我的脚本只会覆盖整个表格。我希望其他数据是相同的。

python脚本:

beforeEach(inject(function ($injector) {
    service = $injector.get("myService");       
}));

it("should have myfunction function", function () {
    expect(angular.isFunction(service.myfunction)).toBe(true);
});

脚本之前的Excel工作表:

enter image description here

脚本之后的Excel表格:

enter image description here

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

1 个答案:

答案 0 :(得分:4)

覆盖是由于使用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")