为了账号安全,请及时绑定邮箱和手机立即绑定

如何将Excel表格保存到原始工作簿中?

如何将Excel表格保存到原始工作簿中?

慕标琳琳 2023-09-05 20:25:34
我有一个这样的函数: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')
查看完整描述

1 回答

?
繁花不似锦

TA贡献1851条经验 获得超4个赞

要在同一个 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)


查看完整回答
反对 回复 2023-09-05
  • 1 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信