【问题标题】:How to save excel sheet to the original workbook?如何将excel表保存到原始工作簿?
【发布时间】:2021-01-11 05:51:21
【问题描述】:

我有这样的功能:

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)

并且我需要保留相同的功能,而不是将那张纸写入新文件。我需要编辑该特定工作表并将其保存回包含其他工作表的工作簿。

编辑(更多解释):我在工作簿中有 4 张工作表,而只有一张工作表 (Sheet3) 我需要使用上述功能,然后将其保存回工作簿。

这也不起作用,在我保存时指定工作表名称:

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')

【问题讨论】:

  • 试试pandas.DataFrame.to_excel(),在那里你可以定义一张表
  • 您能否提供一个示例,说明我将如何在我的场景中使用它?
  • @mastercool 你检查过文档吗?
  • 是的,我有,但我无法让它正常工作。检查我的更新

标签: python python-3.x excel pandas pandas.excelwriter


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2022-10-30
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多