问题
I need to copy data from a text file to an excel file, but without overwriting the old data.
my code:
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:
You are not loading the existing excel file. You are creating a new one every time. Another change I would suggest is to create a new sheet instead of renaming the active one as it will overwrite data in active sheet. Following is the code which reads text from file and writes to a new sheet every time you run the script. I have added some comment for highlighting the changes made:
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
来源:https://stackoverflow.com/questions/45412115/write-into-excel-file-without-overwriting-old-content-with-openpyxl