2017-07-31 916 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 
相關問題