如何将excelsheet保存到原工作簿?

How to save excel sheet to the original workbook?

我有这样的功能:

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='Sheet3')
        print(df)

        # duplicate the rows:
        dup_df = pd.concat([df, df], ignore_index=True)

        # using openpyxl
        with pd.ExcelWriter(new_loc) as writer:
            dup_df.to_excel(writer)

而且我需要保留相同的功能,而不是将 sheet 写入新文件。我需要编辑那个特定的 sheet 并将其保存回我的工作簿中还有其他 sheets.

编辑(更多解释):我在一个工作簿中有 4 个 sheet,只有一个 sheet (Sheet3) 我需要使用上面的功能,然后将其保存回工作簿.

这也不行,保存时指定sheet名称:

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:
        dup_df = pd.concat([df, df], ignore_index=True)

        # using openpyxl
        with pd.ExcelWriter(new_loc) as writer:
            dup_df.to_excel(writer, sheet_name='GTL | GWL Disclosures')

要在同一个 excel 中添加新闻 sheet,您必须以追加模式打开文件。 看看下面的代码:

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)