如何在现有 Excel sheet 下方写入数据帧而不丢失数据透视表 table sheet 中 excel 的切片器?
How to write dataframe below an existing Excel sheet without losing slicer of excel in pivot table sheet?
我正在使用 openpyxl 模块将 pandas 数据框附加到现有 excel sheet 下方。但问题是我的 excel sheet 在 pivot table 中的切片器在执行此任务时被破坏了。我尝试了很多方法来找到它的解决方案,但我认为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()
我看到可以使用 xlwings 和 win32com 来执行此操作,但不确定如何使用这些库执行此操作。我想问一下如何在现有 excel 文件下方附加数据框而不丢失我 excel 的数据透视表 sheet 中的切片器
我们可以在不使用 openpyxl 的情况下执行此操作的方法,因为我认为 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)
我已经尝试了所有可能的解决方案,最后我可以说使用 openpyxl 是不可能的。除了 xlwings,我们可以使用 openpyxl library.xlwings 库处理速度非常快。我们可以在 code.By 的帮助下将数据帧附加到 excel sheet 下面,这样切片器值就不会丢失或删除。
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
希望我清楚。这是我找到的最佳解决方案
我正在使用 openpyxl 模块将 pandas 数据框附加到现有 excel sheet 下方。但问题是我的 excel sheet 在 pivot table 中的切片器在执行此任务时被破坏了。我尝试了很多方法来找到它的解决方案,但我认为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()
我看到可以使用 xlwings 和 win32com 来执行此操作,但不确定如何使用这些库执行此操作。我想问一下如何在现有 excel 文件下方附加数据框而不丢失我 excel 的数据透视表 sheet 中的切片器 我们可以在不使用 openpyxl 的情况下执行此操作的方法,因为我认为 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)
我已经尝试了所有可能的解决方案,最后我可以说使用 openpyxl 是不可能的。除了 xlwings,我们可以使用 openpyxl library.xlwings 库处理速度非常快。我们可以在 code.By 的帮助下将数据帧附加到 excel sheet 下面,这样切片器值就不会丢失或删除。
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
希望我清楚。这是我找到的最佳解决方案