Skip to content Skip to sidebar Skip to footer

How To Save Excel Sheet To The Original Workbook?

I have a function like this: def DuplicateEachRow(): import pandas as pd import pathlib full_path = str(pathlib.Path().absolute()) + '\\' + new_loc

Solution 1:

To add a news sheet in the same excel you have to open the file in mode append. Have a look at the code below:

def DuplicateEachRow():
    import pandas as pd
    import pathlib
    full_path = str(pathlib.Path().absolute()) + '\\' + new_loc

    df = pd.read_excel(full_path, header=None, sheet_name='GTL | GWL Disclosures')
    print(df)

    # duplicate the rows:
    # keep the index, so you can sort the rows after
    dup_df = pd.concat([df, df])
    #sort the rows by the index so you have the duplicate one just after the initial one
    dup_df.sort_index(inplace=True)

    # using openpyxl
    #open the file in append mode 
    with pd.ExcelWriter(new_loc, mode='a') as writer:
        #use a new name for the new sheet
        #don't save the header (dataframe columns names) and index (dataframe row names) in the new sheet  
        dup_df.to_excel(writer, sheet_name='Sheet3', header=None, index=None)

Post a Comment for "How To Save Excel Sheet To The Original Workbook?"