有没有办法在不指定列范围的情况下使用 xlsxwriter 将自动筛选器添加到所有列?

Is there a way to add autofilter to all columns using xlsxwriter without specifying a column range?

我有一个数据框,我正在使用 xlsxwriter 写入 excel,我希望将自动过滤器应用到电子表格中 header 不为空的所有列,而无需指定范围(例如 A1:D1)。有什么办法吗?

您需要以某种方式指定范围,但您可以根据数据框的 shape() 以编程方式指定范围。

例如:

import xlsxwriter
import pandas as pd

df = pd.DataFrame({'A' : [1, 2, 3, 4, 5, 6, 7, 8],
                   'B' : [1, 2, 3, 4, 5, 6, 7, 8],
                   'C' : [1, 2, 3, 4, 5, 6, 7, 8],
                   'D' : [1, 2, 3, 4, 5, 6, 7, 8]})

writer = pd.ExcelWriter('test.xlsx', engine = 'xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

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

# Apply the autofilter based on the dimensions of the dataframe.
worksheet.autofilter(0, 0, df.shape[0], df.shape[1])

workbook.close()
writer.save()

输出:

在to_excel()函数中设置index=False

import xlsxwriter
import pandas as pd

df = pd.DataFrame({'A' : [1, 2, 3, 4, 5, 6, 7, 8],
               'B' : [1, 2, 3, 4, 5, 6, 7, 8],
               'C' : [1, 2, 3, 4, 5, 6, 7, 8],
               'D' : [1, 2, 3, 4, 5, 6, 7, 8]})

writer = pd.ExcelWriter('test.xlsx', engine = 'xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1', index=False)
# Get the xlsxwriter objects from the dataframe writer object.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']
# Apply the autofilter based on the dimensions of the dataframe.
worksheet.autofilter(0, 0, df.shape[0], df.shape[1]-1)
workbook.close()

enter image description here