如何使用 xlswritter 在单个 sheet 中对多个数据帧使用自动过滤器

How to use auto filter for multiple data frame in a single sheet using xlswritter

我正在使用 xlswriter 将数据帧写入 excel sheet。我在同一个 sheet 上有两个数据框,我想为这两个数据框应用自动过滤器。

如果我应用以下规则,它仅适用于 F1:Q1。有什么办法可以将自动过滤器添加到数据框

worksheet.autofilter('A1:D1')
 worksheet.autofilter('F1:Q1')

我尝试了以下但删除了所有条件格式和数据框列

worksheet1.add_table('A1:D4')
worksheet1.add_table('F1:Q15')

在 Excel 中不能有超过一个工作表自动筛选器。

但是,您可以将数据框添加为表格,每个表格都有一个自动过滤器。这是一个数据框的示例:

import pandas as pd

# Create a Pandas dataframe from some data.
df = pd.DataFrame({
    'Country':    ['China',    'India',    'United States', 'Indonesia'],
    'Population': [1404338840, 1366938189, 330267887,       269603400],
    'Rank':       [1,          2,          3,               4]})

# Order the columns if necessary.
df = df[['Rank', 'Country', 'Population']]

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_table.xlsx', engine='xlsxwriter')

# Write the dataframe data to XlsxWriter. Turn off the default header and
# index and skip one row to allow us to insert a user defined header.
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False, index=False)

# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']

# Get the dimensions of the dataframe.
(max_row, max_col) = df.shape

# Create a list of column headers, to use in add_table().
column_settings = []
for header in df.columns:
    column_settings.append({'header': header})

# Add the Excel table strucure. Pandas will add the data.
worksheet.add_table(0, 0, max_row, max_col - 1, {'columns': column_settings})

# Make the columns wider for clarity.
worksheet.set_column(0, max_col - 1, 12)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

输出:

另请参阅 XlsxWriter 文档中的 Working with Tables