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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48280260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:03:41  来源:igfitidea点击:

How to add sheet to existing excel file with pandas?

pythonexcelpandas

提问by cat

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()

I get an error AttributeError: 'Workbook' object has no attribute 'add_worksheet'

我收到一个错误 AttributeError: 'Workbook' object has no attribute 'add_worksheet'

回答by cat

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()