简体   繁体   English

如何在现有 Excel 工作表下方写入数据框而不会丢失数据透视表中的 excel 切片器?

[英]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.我正在使用 openpyxl 模块将 pandas 数据框附加到现有的 Excel 工作表下方。 But problem is my slicer of excel sheet in pivot table is getting destroyed while doing this task.但问题是我在数据透视表中的 excel 工作表切片器在执行此任务时被破坏了。 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.我尝试了很多方法来找到它的解决方案,但我认为 openpyxl 没有办法避免这种情况。

I am using following method to achieve it with openpyxl-我正在使用以下方法来实现它与 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.我已经看到 xlwings 和 win32com 可以做到这一点,但不确定如何使用这些库来做到这一点。 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.我想问一下如何在现有的 excel 文件下附加数据框而不丢失我的 excel 数据透视表中的切片器我们可以在不使用 openpyxl 的情况下完成它的方式,因为我认为 openpyxl 没有可用的方法。 I am getting following warning with openpyxl我收到 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.我已经尝试了所有可能的解决方案,最后我可以说 openpyxl 是不可能的。 In alternate to xlwings we can use openpyxl library.xlwings library is very fast in processing.作为 xlwings 的替代,我们可以使用 openpyxl 库。xlwings 库的处理速度非常快。 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.我们可以在以下代码的帮助下将数据框附加到 Excel 表格下方。通过这种方式,切片器值不会丢失或删除。

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希望我很清楚。这是我找到的最好的解决方案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在忽略索引列值的情况下在现有 Excel 工作表下方写入数据框? - How to write dataframe below an existing Excel Sheet with ignoring index column value? Python Excel 在现有工作表中写入 DataFrame - Python Excel write a DataFrame in an existing sheet 使用 openpyxl 在 excel 下方附加数据框时,我的 excel 表中的切片器被破坏 - Slicer in my excel sheet get destroyed while appending dataframe below excel using openpyxl 如何在不先导出数据框的情况下写入 Excel 工作表? - How to write to an Excel sheet without exporting a dataframe first? 如何将数据框附加到现有的Excel工作表? - How to append a dataframe to existing excel sheet? Pandas 数据框到 excel 文件中的特定工作表而不会丢失格式 - Pandas dataframe to specific sheet in a excel file without losing formatting 无法使用 pandas 将完整的 pivot 表写入现有 excel 工作簿中的新工作表 - Unable to write full pivot table to a new sheet in an existing excel workbook using pandas pandas pivot_table 写入 excel 输出空工作表 - pandas pivot_table write to excel outputs empty sheet Python:将数据框写入到现有的Excel中,其中包含带有图像的工作表 - Python: Write a dataframe to an already existing excel which contains a sheet with images 打开现有 Excel 文件、清除现有工作表并将数据框写入该工作表的最佳方法 - Best way to open existing excel file, clear an existing sheet and write dataframe to that sheet
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM