Vecchia domanda, ma immagino che alcune persone lo cerchino ancora, quindi ...
Trovo questo metodo carino perché tutti i fogli di lavoro vengono caricati in un dizionario di coppie di nomi di fogli e dataframe, creato dai panda con l'opzione sheetname = None. È semplice aggiungere, eliminare o modificare fogli di lavoro tra la lettura del foglio di calcolo nel formato dict e la riscrittura dal dict. Per me xlsxwriter funziona meglio di openpyxl per questa particolare attività in termini di velocità e formato.
Nota: le future versioni di panda (0.21.0+) cambieranno il parametro "sheetname" in "sheet_name".
# read a single or multi-sheet excel file
# (returns dict of sheetname(s), dataframe(s))
ws_dict = pd.read_excel(excel_file_path,
sheetname=None)
# all worksheets are accessible as dataframes.
# easy to change a worksheet as a dataframe:
mod_df = ws_dict['existing_worksheet']
# do work on mod_df...then reassign
ws_dict['existing_worksheet'] = mod_df
# add a dataframe to the workbook as a new worksheet with
# ws name, df as dict key, value:
ws_dict['new_worksheet'] = some_other_dataframe
# when done, write dictionary back to excel...
# xlsxwriter honors datetime and date formats
# (only included as example)...
with pd.ExcelWriter(excel_file_path,
engine='xlsxwriter',
datetime_format='yyyy-mm-dd',
date_format='yyyy-mm-dd') as writer:
for ws_name, df_sheet in ws_dict.items():
df_sheet.to_excel(writer, sheet_name=ws_name)
Per l'esempio nella domanda del 2013:
ws_dict = pd.read_excel('Masterfile.xlsx',
sheetname=None)
ws_dict['Main'] = data_filtered[['Diff1', 'Diff2']]
with pd.ExcelWriter('Masterfile.xlsx',
engine='xlsxwriter') as writer:
for ws_name, df_sheet in ws_dict.items():
df_sheet.to_excel(writer, sheet_name=ws_name)