如何在不更改/删除其他工作表的情况下添加/覆盖现有xlsx文件的工作表

时间:2019-05-15 11:52:32

标签: python

我有一个名为'Results'的xlsx文件,带有工作表'Daily','DHW','SH'。 我需要使用“天”数据框更新每日结果,以便将“每日”工作表中的旧数据删除并替换为新的“天”数据框。 不得修改或删除工作表“ DHW”和“ SH”。谁能帮我吗?

writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
days.to_excel(writer, sheet_name = 'Daily')
writer.save()
writer.close()

这就是我尝试过的方法,但我又放下了其他纸

2 个答案:

答案 0 :(得分:0)

使用append_df_to_excel辅助功能:

import pandas as pd

def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False,
                       **to_excel_kwargs):
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.

    Parameters:
      filename : File path or existing ExcelWriter
                 (Example: '/path/to/file.xlsx')
      df : dataframe to save to workbook
      sheet_name : Name of sheet which will contain DataFrame.
                   (default: 'Sheet1')
      startrow : upper left cell row to dump data frame.
                 Per default (startrow=None) calculate the last row
                 in the existing DF and write to the next row...
      truncate_sheet : truncate (remove and recreate) [sheet_name]
                       before writing DataFrame to Excel file
      to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
                        [can be dictionary]

    Returns: None
    """
    from openpyxl import load_workbook

    import pandas as pd

    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl')

    # Python 2.x: define [FileNotFoundError] exception if it doesn't exist
    try:
        FileNotFoundError
    except NameError:
        FileNotFoundError = IOError


    try:
        # try to open an existing workbook
        writer.book = load_workbook(filename)

        # get the last row in the existing Excel sheet
        # if it was not specified explicitly
        if startrow is None and sheet_name in writer.book.sheetnames:
            startrow = writer.book[sheet_name].max_row

        # truncate sheet
        if truncate_sheet and sheet_name in writer.book.sheetnames:
            # index of [sheet_name] sheet
            idx = writer.book.sheetnames.index(sheet_name)
            # remove [sheet_name]
            writer.book.remove(writer.book.worksheets[idx])
            # create an empty sheet [sheet_name] using old index
            writer.book.create_sheet(sheet_name, idx)

        # copy existing sheets
        writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
    except FileNotFoundError:
        # file does not exist yet, we will create it
        pass

    if startrow is None:
        startrow = 0

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()


days = pd.DataFrame(data={'col1': ['Monday'], 'col2': ['Tuesday']})
append_df_to_excel('Results.xlsx', days, sheet_name='Daily', index=False)

答案 1 :(得分:0)

# add new sheet to existing excel file without deleting any sheet
file_path='D:\example.xlsx' # path for exist file
workbook1 = openpyxl.load_workbook(file_path)
writer = pd.ExcelWriter(file_path, engine='openpyxl')
writer.book = workbook1
df.to_excel(writer, sheet_name='Finally', index=True, index_label="No.")
writer.save()
writer.close()