如何使用pandas将工作表添加到现有excel文件?

时间:2018-01-16 11:31:18

标签: python excel pandas

import pandas as pd
from openpyxl import load_workbook


book = load_workbook('test.xlsx')
writer = pd.ExcelWriter('test.xlsx') 
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df = pd.DataFrame({'a':[1,3,5,7,4,5,6,4,7,8,9],
                   'b':[3,5,6,2,4,6,7,8,7,8,9]})
df.to_excel(writer, sheet_name='tab_name', index = False)

writer.save()

我收到错误 AttributeError:'Workbook'对象没有属性'add_worksheet'

1 个答案:

答案 0 :(得分:0)

import pandas as pd
from openpyxl import load_workbook

fn = 'test.xlsx'

df = pd.read_excel(fn, header=None)
df2 = pd.DataFrame({'a':[1,3,5,7,4,5,6,4,7,8,9],
                   'b':[3,5,6,2,4,6,7,8,7,8,9]})

writer = pd.ExcelWriter(fn, engine='openpyxl')
book = load_workbook(fn)
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

df.to_excel(writer, sheet_name='tab_name', header=None, index=False)
df2.to_excel(writer, sheet_name='tab_name', header=None, index=False,
             startcol=7,startrow=6)

writer.save()