简体   繁体   中英

How to write dataframe below an existing Excel sheet without losing slicer of excel in pivot table sheet?

I am using openpyxl module to append pandas dataframe below an existing excel sheet. But problem is my slicer of excel sheet in pivot table is getting destroyed while doing this task. I have tried many ways to find the solution of it, but I think there is no way available with openpyxl to avoid this situation.

I am using following method to achieve it with openpyxl-

#HELPER FUNCTION TO APPEND DATAFRAME BELOW EXCEL FILE
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', index=False)

    # 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,data_only=True)

        # 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 = 1

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

    # save the workbook
    writer.save()

I have seen that xlwings and win32com is available to do it, but not sure how to do it with these libraries. I want to ask how to append dataframe below existing excel file without losing slicer in pivot sheet of my excel The way by which we can do it without using openpyxl because I think there is no way available with openpyxl. I am getting following warning with openpyxl

C:\Users\Desktop\PycharmProjects\MyProject\venv\lib\site-packages\openpyxl\worksheet\_reader.py:292: UserWarning: Slicer List extension is not supported and will be removed
      warn(msg)

I have tried all the possible solutions and finally I can say that it is not possible with openpyxl. In alternate to xlwings we can use openpyxl library.xlwings library is very fast in processing. We can append the dataframe below the excel sheet with the help of following code.By this way slicer values do not loose or remove.

import xlwings as xw
import pandas as pd
df = pd.read_excel("File_to_append.xlsx")
wb = xw.Book(r"Existing_Excel.xlsx")
ws = wb.sheets('Sheet1')  #Name of sheet where to append df
ws.cells(cell_row_number,cell_column_number).options(index=False, header=False).value = df
#Here cell_row_number and cell_column_number are integer valuesof row number and column number to append data

Hope I am clear .This is the best solution I have found

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM