Python如何使用ExcelWriter写入现有工作表

时间:2016-01-12 13:21:24

标签: python pandas xlsxwriter

我正在尝试使用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)

但问题是这样做输出只是函数的第二次调用,就像函数覆盖整个工作簿一样。我想我需要加载本案例中已经存在的工作簿? 有帮助吗?

3 个答案:

答案 0 :(得分:9)

使用load_book中的openpyxl - 请参阅xlsxwriteropenpyxl文档:

import pandas as pd
from openpyxl import load_workbook

book = load_workbook('test.xlsx')
writer = pd.ExcelWriter('test.xlsx', engine='openpyxl') 
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()

答案 1 :(得分:1)

您也可以尝试使用以下方法创建Excel电子表格:

import pandas as pd

def generate_excel(csv_file, excel_loc, sheet_):
    writer = pd.ExcelWriter(excel_loc)
    data = pd.read_csv(csv_file, header=0, index_col=False)
    data.to_excel(writer, sheet_name=sheet_, index=False)
    writer.save()
    return(writer.close())

尝试一下,让我知道您的想法。

答案 2 :(得分:0)

Pandas version 0.24.0添加了mode关键字,该关键字使您可以追加到excel工作簿,而不必跳过我们以前必须做的工作。只需使用mode='a'将工作表附加到现有工作簿即可。

来自the documentation

with ExcelWriter('path_to_file.xlsx', mode='a') as writer:
     df.to_excel(writer, sheet_name='Sheet3')