Openpyxl: How to add filters to all columns

偶尔善良 提交于 2019-12-10 13:42:07

问题


I can open a worksheet, how do I add the little filter menus to all columns without turning on any filters?

I can do it in xlsxwriter with

worksheet.autofilter(0, 0, 0, num_of_col)

How do I do it in openpyxl?


回答1:


This post helped me answer my question, but instead of creating the variable for "FullRange", you can simply call ws.dimensions and it will return a string value with your range from "A1:XX". I used this to apply filters to my entire excel spreadsheet.

import openpyxl as px

wb= px.load_workbook('Data/Test01.xlsx')
ws = wb.active

ws.auto_filter.ref = ws.dimensions

wb.save('Data/Test03.xlsx')



回答2:


All you need to do is to set worksheet.auto_filter.ref to the full range of worksheet cells.

import openpyxl
from openpyxl.utils import get_column_letter

workbook = openpyxl.load_workbook('Data/Test01.xlsx')
worksheet = workbook['Sheet1']

FullRange = "A1:" + get_column_letter(worksheet.max_column) \
+ str(worksheet.max_row)
worksheet.auto_filter.ref = FullRange

workbook.save('Data/Test03.xlsx')


来源:https://stackoverflow.com/questions/51566349/openpyxl-how-to-add-filters-to-all-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!