简体   繁体   English

如何在 .xlsm 文件中使用 Pandas 将数据框添加到现有 Excel 工作表

[英]How to add a dataframe to an existing Excel sheet with Pandas, on a .xlsm file

I want to import the values from a Pandas dataframe into an existing Excel sheet.我想将 Pandas 数据框中的值导入到现有的 Excel 工作表中。 I want to insert the data inside the sheet without deleting what is already there in the other cells (like formulas using those datas etc).我想在工作表中插入数据而不删除其他单元格中已有的内容(例如使用这些数据的公式等)。

I tried using data.to_excel like:我尝试使用 data.to_excel 像:

writer = pd.ExcelWriter(r'path\TestBook.xlsm')    
data.to_excel(writer, 'Sheet1', startrow=1, startcol=11, index = False)    
writer.save()

The problem is that this way i overwrite the entire sheet.问题是这样我会覆盖整个工作表。 Is there a way to only add the dataframe?有没有办法只添加数据框? It would be perfect if I could also keep the format of the destination cells.如果我还可以保留目标单元格的格式,那就太完美了。 Thanks谢谢

I found a good solution for it.我找到了一个很好的解决方案。 Xlwings natuarally supports pandas dataframe: https://docs.xlwings.org/en/stable/datastructures.html#pandas-dataframes Xlwings 自然支持熊猫数据帧: https ://docs.xlwings.org/en/stable/datastructures.html#pandas-dataframes

The to_excel function provides a mode parameter to insert (w) of append (a) a data frame into an excel sheet, see below example: to_excel 函数提供了一个模式参数,用于将数据框的 append (a) 的 (w) 插入到 Excel 工作表中,请参见以下示例:

with pd.ExcelWriter(p_file_name, mode='a') as writer:
    df.to_excel(writer, sheet_name='Data', startrow=2, startcol=2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM