写入excel文件而不用openpyxl覆盖旧内容 [英] write into excel file without overwriting old content with openpyxl

查看:853
本文介绍了写入excel文件而不用openpyxl覆盖旧内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to copy data from a text file to an excel file, but without overwriting the old data.

我的代码:

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

推荐答案

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

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

这篇关于写入excel文件而不用openpyxl覆盖旧内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆