Created
October 24, 2019 19:27
-
-
Save jkyeung/3ca2fe882d4997365460f622e4fa17d0 to your computer and use it in GitHub Desktop.
Autofilter demo in Python with XlsxWriter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import os | |
import xlsxwriter | |
os.chdir(sys.path[0]) # ensure working directory is the script directory | |
headings = ['Alpha', 'Beta', 'Gamma', 'Delta'] | |
data = [ | |
list(range(4)), | |
[2 * x for x in range(4)], | |
[3 * x for x in range(4)], | |
[x + 5 for x in range(4)]] | |
filter_column = 1 # zero-indexed, so this is column B | |
filter_selections = [2, 3] | |
with xlsxwriter.Workbook(__file__.replace('.py', '.xlsx')) as wb: | |
ws = wb.add_worksheet() | |
ws.write_row(0, 0, headings) | |
for rx, row in enumerate(data, start=1): | |
ws.write_row(rx, 0, row) | |
if data[rx - 1][filter_column] not in filter_selections: | |
ws.set_row(rx, options={'hidden': True}) | |
ws.autofilter('A1:C1') # just filter the first 3 columns | |
ws.filter_column_list(filter_column, filter_selections) | |
print('Done.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment