2017-07-31 99 views
-1

我需要将数据从文本文件复制到excel文件,但不覆盖旧数据。使用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 

回答

2

你不加载现有的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 
相关问题