如何将数据框附加到现有Excel工作表?

时间:2016-08-21 19:32:37

标签: python pandas xlrd xlsxwriter

该函数被多次调用。我保留了一个计数,以便如果它第一次调用,就会创建一个工作簿。然后我使用pd.ExcelWrite()写入该工作簿。下次执行else:并打开相同的工作簿。选择它的第一张纸,找到它的最后一行。 DataFrame写在该行上。 这是我的代码:

def WriteFile (df):
  if count1 == 1:
      workbook = xlsxwriter.Workbook('pandas_simple.xlsx')
      writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
      df.to_excel(writer, index=False )
      workbook.close()
  else:
      book = open_workbook('pandas_simple.xlsx')
      sheet_names = book.sheet_names()
      sheet = book.sheet_by_name(sheet_names[0])
      row = sheet.nrows
      writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
      df.to_excel(writer, index=False, header=False, startrow = row )

我得到了这个例外:

Exception Exception: Exception('Exception caught in workbook destructor. Explicit close() 
may be required for workbook.',) in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook 
object at 0x000000000A143860>> ignored Exception

执行代码后,我的pandas_simple.xlsx也是空的。我究竟做错了什么?

2 个答案:

答案 0 :(得分:3)

感谢@ski。

请在同一问题上提及他的答案

How to write to an existing excel file without overwriting data (using pandas)?

import pandas
from openpyxl import load_workbook

book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl') 
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()

答案 1 :(得分:2)

你可以这样做:

df = pd.DataFrame(np.arange(1, 31), columns=['val'])
fn = 'd:/temp/test.xlsx'
count = 0

writer = pd.ExcelWriter(fn)

for chunk in np.split(df, 3):
    chunk.to_excel(writer, index=False, header=(count==0), startrow=count+(count!=0))
    count += len(chunk)

writer.save()

结果:

enter image description here