Python如何使用ExcelWriter写入现有工作表 [英] Python How to use ExcelWriter to write into an existing worksheet

查看:2871
本文介绍了Python如何使用ExcelWriter写入现有工作表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ExcelWriter将一些信息写入/添加到包含多个工作表的工作簿中. 第一次使用该功能时,我正在使用一些数据创建工作簿.在第二个呼叫中,我想在工作簿中的所有表的不同位置添加一些信息.

I am trying to use ExcelWriter to write/add some information into a workbook that contains multiple sheets. First time when I use the function, I am creating the workbook with some data. In the second call, I would like to add some information into the workbook in different locations into all sheets.

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两次调用此函数,以在不同位置打印我的数据.

In the main code I call this function twice with different col to print out my data in different locations.

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

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

But the problem is that doing so the output is just the second call of the function as if the function overwrites the entire workbook. I guess I need to load the workbook that already exists in this case? Any help?

推荐答案

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

Use load_book from openpyxl - see xlsxwriter and openpyxl docs:

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

这篇关于Python如何使用ExcelWriter写入现有工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆