当前位置: 代码迷 >> 综合 >> pandas 不覆盖写入 excel 同一张 Sheet 表
  详细解决方案

pandas 不覆盖写入 excel 同一张 Sheet 表

热度:20   发布时间:2024-01-12 18:24:39.0

这里解决的问题是:

用 Pandas 可以不覆盖的写入同一张 Sheet 表,

当然写入不同的表也可以实现,

在 stackoverflow 上看到的代码,

我试了试可以,感谢 stackoverflow 的 MaxU

这里在 jupyter notebook 中实现,python 版本 3.7

我又把全部代码粘贴到vscode中直接运行,

报了未安装openpyxl模块的错误,安装openpyxl模块后,可正常运行

整合起来的版本:https://github.com/findQin/pandas-Excel

我自己写了测试代码,在下面,

第一个部分的代码就是从 stackoverflow 上 copy 的函数 append_df_to_excel() ,

第二个部分的代码测试行不行,分别写入Sheet1表(多次写入不覆盖),Sheet2表。

最后有成功写入的截图为证。

这是 StackOverflow 网页链接

append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2', index=False)

import pandas as pd
from openpyxl import load_workbookdef append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,truncate_sheet=False, **to_excel_kwargs):"""Append a DataFrame [df] to existing Excel file [filename]into [sheet_name] Sheet.If [filename] doesn't exist, then this function will create it.Parameters:filename : File path or existing ExcelWriter(Example: '/path/to/file.xlsx')df : dataframe to save to workbooksheet_name : Name of sheet which will contain DataFrame.(default: 'Sheet1')startrow : upper left cell row to dump data frame.Per default (startrow=None) calculate the last rowin the existing DF and write to the next row...truncate_sheet : truncate (remove and recreate) [sheet_name]before writing DataFrame to Excel fileto_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`[can be dictionary]Returns: None"""# ignore [engine] parameter if it was passedif 'engine' in to_excel_kwargs:to_excel_kwargs.pop('engine')writer = pd.ExcelWriter(filename, engine='openpyxl')# Python 2.x: define [FileNotFoundError] exception if it doesn't exist try:FileNotFoundErrorexcept NameError:FileNotFoundError = IOErrortry:# try to open an existing workbookwriter.book = load_workbook(filename)# get the last row in the existing Excel sheet# if it was not specified explicitlyif startrow is None and sheet_name in writer.book.sheetnames:startrow = writer.book[sheet_name].max_row# truncate sheetif truncate_sheet and sheet_name in writer.book.sheetnames:# index of [sheet_name] sheetidx = writer.book.sheetnames.index(sheet_name)# remove [sheet_name]writer.book.remove(writer.book.worksheets[idx])# create an empty sheet [sheet_name] using old indexwriter.book.create_sheet(sheet_name, idx)# copy existing sheetswriter.sheets = {ws.title:ws for ws in writer.book.worksheets}except FileNotFoundError:# file does not exist yet, we will create itpassif startrow is None:startrow = 0# write out the new sheetdf.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)# save the workbookwriter.save()
# 几个例子用于测试写入 excel 用的
df1 = pd.DataFrame({'One':[1,2,3]})
df2 = pd.DataFrame({'Two':[4,5,6]})
df3 = pd.DataFrame({'Three':[7,8,9]})
df4 = pd.DataFrame({'Four':[10,11,12]})
# 写入 Aho.xlsx 这个 excel 的 sheet1 表的第0行(startrow=0),第0列(startcol=0)
append_df_to_excel('Aho.xlsx', df1, sheet_name='Sheet1', startcol=0,startrow=0,index=False)# 写入sheet1 的第0行(startrow=0),第3列(startcol=3)
append_df_to_excel('Aho.xlsx', df2, sheet_name='Sheet1', startcol=3,startrow=0,index=False)# 写入sheet1 的第0行(startrow=0),第7列(startcol=7)
append_df_to_excel('Aho.xlsx', df3, sheet_name='Sheet1', startcol=7,startrow=0,index=False)# 写入sheet2 的第0行(startrow=0),第0列(startcol=0)
append_df_to_excel('Aho.xlsx', df4, sheet_name='Sheet2', startcol=0,startrow=0,index=False)

-------截图戳这-----

-----截图还有这-----

  相关解决方案