diff --git a/aprendizations/initdb.py b/aprendizations/initdb.py index 8e221f7..6cfe51d 100644 --- a/aprendizations/initdb.py +++ b/aprendizations/initdb.py @@ -5,8 +5,9 @@ Initializes or updates database ''' # python standard libraries -import csv import argparse +import csv +from pandas import read_excel import re from string import capwords @@ -32,11 +33,11 @@ def parse_commandline_arguments(): 'command line. If the database does not exist, a new one' ' is created.') - argparser.add_argument('csvfile', + argparser.add_argument('files', nargs='*', type=str, default='', - help='CSV file to import (SIIUE)') + help='CSV or Excel files to import (SIIUE)') argparser.add_argument('--db', default='students.db', @@ -72,6 +73,30 @@ def parse_commandline_arguments(): # =========================================================================== +def get_students_from_xlsx(filename): + excel_settings = { + 'skiprows': 3, + 'converters': { "Número" : str } + } + students = [] + try: + file = read_excel(filename, **excel_settings) + names = file['Aluno'] + nums = file['Número'] + students = [{ + 'uid': num, + 'name': capwords(re.sub(r'\(.*\)', '', name).strip()) + } for num, name in zip(nums, names)] + except FileNotFoundError as e: + print(f'!!! File {filename} not found !!!') + except ValueError as e: + print(f'!!! File {filename} has wrong format !!!') + except Exception as e: + raise e + + return students + +# =========================================================================== def get_students_from_csv(filename): '''Reads CSV file with enrolled students in SIIUE format. SIIUE names can have suffixes like "(TE)" and are sometimes capitalized. @@ -138,8 +163,13 @@ def main(): # --- make list of students to insert/update students = [] - for csvfile in args.csvfile: - students += get_students_from_csv(csvfile) + for file in args.files: + if file.endswith('.csv'): + students += get_students_from_csv(file) + elif file.endswith('.xlsx'): + students += get_students_from_xlsx(file) + else: + print(f'!!! Ignoring file {file} !!!') if args.admin: students.append({'uid': '0', 'name': 'Admin'}) diff --git a/setup.py b/setup.py index 2975c5c..aac4edc 100644 --- a/setup.py +++ b/setup.py @@ -26,7 +26,9 @@ setup( 'pygments>=2.14', 'sqlalchemy>=2.0.0', 'bcrypt>=4.0.1', - 'networkx>=3.0' + 'networkx>=3.0', + 'pandas>=2.3', + 'openpyxl' ], entry_points={ 'console_scripts': [ -- libgit2 0.21.2