问题描述
我正在使用xlswriter将数据帧写入Excel工作表。我在同一张纸上有两个数据框,并且我想对两个数据框都应用自动过滤器。
如果我应用以下规则,则该规则仅适用于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,max_row,max_col - 1,{'columns': column_settings})
# Make the columns wider for clarity.
worksheet.set_column(0,12)
# Close the Pandas Excel writer and output the Excel file.
writer.save()
输出:
另请参阅XlsxWriter文档中的Working with Tables。