写入excel文件而不用openpyxl覆盖旧内容

时间:2017-07-31 09:30:07

标签: python excel python-2.7 openpyxl

我需要将数据从文本文件复制到excel文件,但不会覆盖旧数据。

我的代码:

import os,sys
from openpyxl import Workbook
from openpyxl.compat import range

wb = Workbook()
Excelfilename = 'LogErrors.xlsx'
ws1 = wb.active
ws1.title = "Historique"
excelData = []
try:
    with open('out.txt') as f:
        for line in f:
            excelData.append([word for word in line.split("\t") if word]) 
    for lines in range(1,len(excelData)):
        for columns in range(1,len(excelData[lines])):
            ws1.cell(column=columns, row=lines, value=excelData[lines][columns-1])
    wb.save(filename = Excelfilename)
except Exception, e:
    print e.message

1 个答案:

答案 0 :(得分:1)

您没有加载现有的Excel文件。你每次都在创造一个新的。我建议的另一个改变是创建一个新工作表而不是重命名活动工作表,因为它将覆盖活动工作表中的数据。以下是每次运行脚本时从文件读取文本并写入新工作表的代码。我添加了一些注释来突出显示所做的更改:

import os,sys
from openpyxl import load_workbook
from openpyxl.compat import range

Excelfilename = 'LogErrors.xlsx'
# Open existing file with load_workbook
wb = load_workbook(Excelfilename)
# Create a new sheet instead of renaming active
ws = wb.create_sheet('Historique')
# You can rename the active if that was intent
excelData = []
try:
    with open('out.txt') as f:
        for line in f:
            excelData.append([word for word in line.split("\t") if word]) 
    # Indices for array start at 0
    for lines in range(0,len(excelData)):
        # Indices for array start at 0
        for columns in range(0,len(excelData[lines])):
            # Column and row indices start at 1
            ws.cell(column=columns+1, row=lines+1, value=excelData[lines][columns-1])
    wb.save(filename = Excelfilename)
except Exception, e: # Don't catch everything, catch what you expect
    print e.message