使用Openpyxl将数据框附加到现有Excel工作表

时间:2018-05-01 18:12:50

标签: excel python-3.x pandas openpyxl

我正在尝试创建一个新的电子表格和工作表,其中包含数据框中的列标题。然后,我想在每个For循环迭代中将新数据附加到工作表。我可能有大量数据,因此认为有必要在每次迭代后将其写入Excel,而不是在最后编写整个DF。 如果我写入已包含该列的电子表格,{em>“将数据附加到现有工作表”代码中的For循环可以正常工作(即给我3行值)我在Excel中创建的标题。但是,当我按照下面的说明运行代码时,我只会得到列标题和上一次For循环迭代的值。我显然错过了一些简单但似乎无法解决的问题。任何帮助将不胜感激

import openpyxl as xl
import pandas as pd
import numpy as np
import datetime as dt

fn = '00test101.xlsx'
# Create new workbook
wb = xl.Workbook()
wb.save(fn)

book = xl.load_workbook(fn)
writer = pd.ExcelWriter(fn,engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
# Write DF column names to new worksheet
DF = pd.DataFrame(columns=['A','B','C'])
DF.to_excel(writer, 'ABC', header=True, startrow=0)
writer.save()

for i in range(3):
    a = np.array([1,3,6]) * i

    # Overwrite existing DF and add data
    DF = pd.DataFrame(columns=['A','B','C'])
    DF.loc[dt.datetime.now()] = a

    # Append data to existing worksheet
    book = xl.load_workbook(fn)
    writer = pd.ExcelWriter(fn,engine='openpyxl')
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
    DF.to_excel(writer, 'ABC', header=None, startrow=book.active.max_row)
    writer.save()

# Remove unwanted default worksheet
wb = xl.load_workbook(fn)
def_sheet = wb.get_sheet_by_name('Sheet')
wb.remove_sheet(def_sheet)
wb.save(fn)

0 个答案:

没有答案