gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:31:37 25 4
gpt4 key购买 nike

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

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

最佳答案

使用 openpyxl 中的 load_book - 参见 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()

关于Python 如何使用 ExcelWriter 写入现有工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34744863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com