Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Openpyxl: How to add filters to all columns

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?

like image 581
azazelspeaks Avatar asked Jul 27 '18 22:07

azazelspeaks


People also ask

Is openpyxl safe?

Is openpyxl safe to use? The python package openpyxl was scanned for known vulnerabilities and missing license, and no issues were found. Thus the package was deemed as safe to use. See the full health analysis review.

Does pandas work with openpyxl?

openpyxl has builtin support for the NumPy types float, integer and boolean. DateTimes are supported using the Pandas' Timestamp type.


2 Answers

You can simply read 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')
like image 79
Robert Hadsell Avatar answered Oct 18 '22 07:10

Robert Hadsell


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')
like image 8
G5W Avatar answered Oct 18 '22 06:10

G5W