如何在输出前自动筛选excelsheet

2024-09-27 07:27:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个脚本创建函数,该脚本从一个api获取数据,该api将数据帧输出到excel工作表。我需要自动筛选(作为可选参数)。你知道吗

我差不多完成了,但是通过下面的解释不断得到一个属性错误“Worksheet”对象没有属性“autofilter”

这是我一直在尝试的代码

def generate_xls(df, file_name, sheet_name, column_names=None, auto_filter=True):

    if column_names != None:
        df.columns = column_names

    print("appending the data in order...")   

    print("\nCreating excel-file")

    writer = pd.ExcelWriter(file_name + '.xls')    

    df.to_excel(writer,sheet_name,index=False)

    if auto_filter == True:
        for worksheet in writer.sheets.values():  
            worksheet.autofilter(df.columns)            

    writer.save()
    print("Excel-file generated.")

它没有自动过滤功能也能正常工作,但对我来说拥有它真的很重要,因为还有其他人可能需要它。任何建议都太好了!你知道吗


Tags: name脚本noneapidf属性namescolumn
2条回答

我认为您首先需要添加自动过滤器,假设您使用的是OpenPyXl

To add a filter you define a range and then add columns and sort conditions

ws.auto_filter.ref = "A1:B15"
ws.auto_filter.add_filter_column(0, ["Kiwi", "Apple", "Mango"])
ws.auto_filter.add_sort_condition("B2:B15") ```

当然,您可以省略add_filteradd_sort_conditions,并将其留给用户进行配置。You will need to do simply

worksheet.auto_filter.ref = worksheet.dimensions

谢谢你的意见。我在writer对象中使用pandas和xlsxwriter引擎解决了这个问题:

    if auto_filter == True:
        for worksheet in writer.sheets.values():
            row_count = len(df.index)
            column_count = len(df.columns)
            worksheet.autofilter(0, 0, row_count-1, column_count-1)                                
    writer.save()
    print("Excel-file generated.")

相关问题 更多 >

    热门问题