Python project -"Adjusting based on the days in a month" & "Adding multiple statements in a cell through loops without overwriting"

I am using a bunch of for loops to print milestones and their names on an excel sheet. The visuals do not match the day (i.e 28th of feb should be near the end of the cell) and when I try printing multiple milestones in one cell it overwrites the previous content. Note, the imports have already been included in the original script so it is not the potential issue. I would appreciate it if someone could help me tackle this! The code I have is the one below:

    #f1- function to input the information necessary and to handle errors accordingly
    def FileName_and_Number():
        while True:
            try:
               filePath=input("Please enter the path of the Tier~0 file saved: ")
               filePath=filePath.strip() #the strip() function deletes any leading          whitespace causing potential crashes
              Month=input("Please enter the current month for the Milestone update (Jan-Dec): ")
            Year=int(input("Please enter the current year or the year the update is being processed for (xxxx): "))
            Month=Month.lower() #to decrease the chances of potential errors
            return [filePath, Month, Year]
        except ValueError:
            print("Please enter a valid number.")
           
#f2- function that uses the inputted information and opens the T0 file and extracts information- NECESSART? IT IS NOT RETURNING ANYTHING
def OpenFile_and_read(Info):
    try:
        file_open=pd.read_excel(Info[0], index_col=None, header=0, usecols=[3,4,5,9,10,11], skiprows=[0])
                                                                # [Project, Manager, Milestone Name, Baseline date, Revised date, Status] - !!Note, if the format does not match, potential for logical errors are present!!
        #Deleting the empty rows
        empty_counter=0
        for index, row in file_open.iterrows():
            if row.isnull().all():
                empty_counter+=1
            else:  #reseting the counter if a row is non empty
                empty_counter=0

            if empty_counter==2: #NORM SHOULD BE 2
                file_open=file_open.iloc[:index-1]
                break
         
        file_open.to_csv("ProgressCheck.csv") #TO Be deleted
        return file_open
       
    except FileNotFoundError as e:
        print(f'FileNotFoundError: {e}')
    except Exception as e:
        print(f'An error occured: {e}')
   
#f3 returns the corresponding column number
def month_col(monthNum):
    monthNum=int(monthNum)
    col=0
    if monthNum==1:
        col=1
    elif monthNum==2:
        col=2
    elif monthNum==3:
        col=3
    elif monthNum==4:
        col=4
    elif monthNum==5:
        col=5
    elif monthNum==6:
        col=6
    elif monthNum==7:
        col=7
    elif monthNum==8:
        col=8
    elif monthNum==9:
        col=9
    elif monthNum==10:
        col=10
    elif monthNum==11:
        col=11
    elif monthNum==12:
        col=12
       
    return col

#f4- returns the corresponding row number for the visual to print based on the project category
def project_row(projectCategory, UniqueProject_df):
    for index, project in enumerate(UniqueProject_df):
        if project==projectCategory:
            return index


#f5- returns number of characters according to the day to adjust the milestone visuals in the cell
def positionMilestone(day, total_width=80, char_width=2):
    num_chars=total_width//char_width
    print(num_chars)
    position=int((day-1)/31*num_chars)
    print(position)
    return " " *position + "▲"

#f6- returns number of characters according to the day to adjust the milestone name in the cell
def positionName(day, milestoneName, total_width=80, char_width=1):
   
    num_chars=total_width//char_width
    position=int((day-1)/31*num_chars) - 8

    return " " *position + milestoneName


#f7- comparison between the baseline date, the revised date, and the status, and returns
def comparison(workbook, status):
   
    if status=="completed":
        milestone_format=workbook.add_format({'text_wrap':True,'font_size':26, 'font_color': 'blue', 'align': 'center'})
        return milestone_format

    elif status=="delayed":
        milestone_format=workbook.add_format({'text_wrap':True,'font_size':26, 'font_color': 'white', 'align': 'center','border':1})
        return milestone_format
   
    elif status=="canceled":
        milestone_format=workbook.add_format({'text_wrap':True,'font_size':26, 'font_color': 'red', 'align': 'center','border':1})
        return milestone_format

    elif status=="on track" :
        milestone_format=workbook.add_format({'text_wrap':True,'font_size':26, 'font_color': 'green', 'align': 'center','border':1})
        return milestone_format

    elif status=="at risk" :
        milestone_format=workbook.add_format({'text_wrap':True,'font_size':26, 'font_color': 'yellow', 'align': 'center','border':1})
        return milestone_format
    elif status=="not applicable" :
        milestone_format=workbook.add_format({'text_wrap':True,'font_size':26, 'font_color': '#5B5B5B', 'align': 'center','border':1})
        return milestone_format
   
   
    '''if Bmonth!=Rmonth: #Delayed or finished quicker
        print('here')
        col=month_col(Rmonth)
        milestone_format=workbook.add_format({'text_wrap':True,'font_size':20, 'font_color': 'white', 'align': 'center','border':1})
        return milestone_format, col'''

#f- iterative process to go through the data collected and create visuals.
def Visual_and_data_mining(df, information):
    fileName_new=str(information[2])+' Tier0 Milestone Update.xlsx'
    workbook=xlsxwriter.Workbook(fileName_new)
    worksheet=workbook.add_worksheet('Visual')
    year = information[2]
    month = information[1].capitalize()
    title = f'FY{year} Tier 0 Milestones - {month} Status'
    worksheet.write(0, 0, title, workbook.add_format({'bold': True, 'font_name': 'Bombardier Display', 'font_size': 16}))
    print("Excel Workbook Successfully created.")



    wrap_format=workbook.add_format({'text_wrap':True,'bg_color':'#F6F5F3', 'border':1 })
    wrap_format1=workbook.add_format({'text_wrap':True,'bg_color':'#E2E2E1', 'border':1 })
    worksheet.set_column('A:A', 60, wrap_format)
    worksheet.set_column('B:M', 80, wrap_format1)
    worksheet.set_row(2,20)

   
    quarters = ['Q1', 'Q2', 'Q3', 'Q4']
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    worksheet.set_row(3,25) #for the row including the title project and months
    worksheet.write(3,0, 'Project', workbook.add_format({'bold': True, 'font_name': 'Bombardier Display', 'font_size': 14, 'align':'center', 'bg_color':'#9F9E9C', 'border':1}))
    col=1
    for quarter in quarters:
        worksheet.merge_range(2, col, 2, col+2, quarter, workbook.add_format({'bold': True, 'font_name': 'Bombardier Display', 'font_size': 16, 'align':'center','font_color':'white','bg_color':'#4B4846','border':1}))
        for j in range(3):
            current_month=months.pop(0)
            if current_month==month:
                worksheet.write(3, col+j, current_month, workbook.add_format({'bold': True, 'font_name': 'Bombardier Display', 'font_size': 14, 'align':'center','bg_color':'#00FF00','border':1}))
            else:
                worksheet.write(3, col+j, current_month, workbook.add_format({'bold': True, 'font_name': 'Bombardier Display', 'font_size': 14, 'align':'center','bg_color':'#9F9E9C', 'border':1}))
        col += 3



    #creating unique data frames for managers and projects to remove duplicates - the indices of the two data frames match accoringly
    projects = df['Project'].unique()
    managers=df['Manager'].unique()
    project_format=workbook.add_format({'text_wrap':True,'bold': True, 'font_name': 'Bombardier Display', 'font_size':15, 'align':'center'})
    manager_format=workbook.add_format({'text_wrap':True,'italic': True, 'font_name': 'Bombardier Display', 'font_size':12})
    milestone_format=workbook.add_format({'text_wrap':True,'font_size':26, 'font_color': 'blue', 'align': 'center'})
    milestoneName_format=workbook.add_format({'text_wrap':True, 'font_name': 'Bombardier Display', 'font_size':12})
    row_num=4

   
    #for loop to print the project categories
    for project in projects:
       manager=df[df['Project']==project]['Manager'].iloc[0]
       combined=[project_format, project, " \n(", manager_format, manager, ") "]
       worksheet.write_rich_string(row_num ,0, *combined)
       worksheet.set_row(row_num, 75)
       row_num+=1

    #Label !!!!
    #for i in range(len(df)):
    for i in range(4):    
        #Retrieving the milestone name and the status of the milestone
        milestone=str(df.iloc[i,2])
        status=str(df.iloc[i,5])
        status=str(df.iloc[i,5]).strip().lower() if pd.notna(df.iloc[i,5]) else "unknown"

       
        #Baseline Date
        baseline_Date=str(df.iloc[i,3])
        baseline_month=baseline_Date.split('-')[1]
        baseline_day=int(baseline_Date.split('-')[2][:2])

        col=month_col(baseline_month) #Column for the baseline Date
        row=project_row(df.iloc[i,0], projects)
        row=row+4 #To match the rows on the excel file NOTE- row does NOT change with a revised date, only column (month)

        aligned_text=positionMilestone(baseline_day)
        milestoneName=positionName(baseline_day, milestone)
        mm_combined=[milestone_format, aligned_text, '\n', milestoneName_format, milestoneName]
        worksheet.write_rich_string(row, col, *mm_combined) #Visualizing the baseline milestones
       
        #Revised date
        revised_Date=str(df.iloc[i,4])
       
        if revised_Date!='NaT':
           
            milestone_format1=comparison(workbook, status)
           
            #Printing the revised milestones according to their formatting
            mm_combined=[milestone_format1, aligned_text, '\n',   milestoneName_format, milestoneName]
            worksheet.write_rich_string(row, col, *mm_combined)


            revised_month=revised_Date.split('-')[1]
            revised_day=revised_Date.split('-')[2][:2]
            revised_year=revised_Date.split('-')[0]

        else:
            continue
           

    workbook.close()
    print("Excel Workbook Successfully closed.")
               
   
#Calling the functions accordingly
Information=FileName_and_Number()
df=OpenFile_and_read(Information)
call=Visual_and_data_mining(df, Information)

Just FYI, the width of the cells in the excel sheet are set to be 80, and the font of the triangles are 26, and the milestone name is 12.

Upvotes: 0

Views: 19

Answers (0)

Related Questions