附加到现有的excel而不更改格式

时间:2019-11-04 11:27:04

标签: python excel pandas

我正在尝试从其他excel / csv工作表中获取数据,并将其附加到现有工作簿/工作表中。下面的代码在追加方面起作用,但是,它不仅删除了我追加的工作表的格式,还删除了工作簿中所有其他工作表的格式。

据我了解,发生这种情况的原因是因为我正在将整个ExcelWorkbook作为字典阅读,将其转换为Pandas Dataframe,然后将其重写为Excel。但是我不确定如何去做。

如何修改代码以使其仅添加所需的数据,而保持其他所有内容不变?熊猫是做这件事的不正确方法吗?

import os  
import pandas as pd  
import openpyxl  


#Read Consolidated Sheet as Dictionary
#the 'Consolidation' excel sheet has 3 sheets: 
#Consolidate, Skip1, Skip2

ws_dict = pd.read_excel('.\Consolidation.xlsx', sheet_name=None)

#convert relevant sheet to datafarme
mod_df = ws_dict['Consolidate']

#check that mod_df is the 'Consolidate' Tab
mod_df

#do work on mod_df
#grab extra sheets with data and make into pd dataframes
excel1 = 'doc1.xlsx'
excel2 = 'doc2.xlsx'

df1 = pd.read_excel(excel1)
df1 = df1.reset_index(drop=True)

df2 = pd.read_excel(excel2)
df2 = df2.reset_index(drop=True)

#concate the sheets
mod_df = pd.concat([mod_df, df1, df2], axis=0, ignore_index = True, sort=False)

#reassign the modified to the sheet
ws_dict['Consolidate'] = mod_df

#write to the consolidation workbook
with pd.ExcelWriter('Consolidation.xlsx', engine='xlsxwriter') as writer:
    for ws_name, df_sheet in ws_dict.items():
        df_sheet.to_excel(writer, sheet_name=ws_name, index=False)

0 个答案:

没有答案