2016-01-12 26 views
2

我想使用ExcelWriter将一些信息写入/添加到包含多个工作表的工作簿中。 第一次使用该函数时,我正在用一些数据创建工作簿。在第二次电话会议中,我想将不同位置的工作簿中的一些信息添加到所有工作表中。Python如何使用ExcelWriter写入现有的工作表

def Out_Excel(file_name,C,col): 
    writer = pd.ExcelWriter(file_name,engine='xlsxwriter') 
    for tab in tabs: # tabs here is provided from a different function that I did not write here to keep it simple and clean 
     df = DataFrame(C) # the data is different for different sheets but I keep it simple in this case 
     df.to_excel(writer,sheet_name = tab, startcol = 0 + col, startrow = 0) 
    writer.save() 

在主代码中,我将这个函数用不同的col调用两次,以在不同的位置打印出我的数据。

Out_Excel('test.xlsx',C,0) 
Out_Excel('test.xlsx',D,10) 

但问题是,这样做的输出只是函数的第二次调用,就好像该函数覆盖整个工作簿一样。我想我需要加载在这种情况下已经存在的工作簿? 有什么帮助吗?

回答

5

使用load_bookopenpyxl - 见xlsxwriteropenpyxl文档:

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.to_excel(writer, sheet_name='tab_name', other_params) 

writer.save() 
+0

感谢您的评论。按照你的建议,我要创建工作簿的第一次,然后每当需要使用load_book。我这样做,但我得到以下错误:TypeError:copy()得到了一个意想不到的关键字参数'字体' – Hamed

+0

请参阅http://stackoverflow.com/questions/30102232/pandas-can-not-write-to-excel-file – Stefan

+0

只需双重检查,并使用'pandas 0.17.1'和'openpyxl 2.3.1'正常工作。 – Stefan

相关问题