Python Forum
Is it possible to extract 1 or 2 bits of data from MS project files?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is it possible to extract 1 or 2 bits of data from MS project files?
#1
We have a weekly meeting with management to present current status on few projects that are going on.. Im looking to extract the % complete from each project and update an excel file for our presentation.

Can python access and extract that value? I dont need to modify or anything else, i just need to extract that value to update our excel dashboard.
Reply
#2
Search for packages at: https://pypi.org/

This looks interesting: https://pypi.org/project/mpxj/
Reply
#3
All my google searching and that site never came up in my results, maybe i was to general on my search, ill def take a look at this and see what it can offer me for the functionality im looking for.

thank you
Reply
#4
So i tried this example to open and return tasks, but get an error that it cannot open the file, the file and script are in the same directory for this test.

import win32com.client

def list_task_attributes(file_path):
    ms_project_app = None
    try:
        # Create an instance of the Microsoft Project application
        ms_project_app = win32com.client.Dispatch("MSProject.Application")

        # Open the Microsoft Project file in read-only mode
        ms_project_app.FileOpen(file_path, ReadOnly=True)

        # Access all tasks and list their attributes
        for task in ms_project_app.ActiveProject.Tasks:
            print(f"\nTask ID: {task.ID}")
            for attribute in dir(task):
                # Exclude attributes that start with '__' (internal attributes)
                if not attribute.startswith('__'):
                    value = getattr(task, attribute)
                    print(f"{attribute}: {value}")

    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        try:
            # Close the Microsoft Project file only if it's open
            if ms_project_app and ms_project_app.ActiveProject:
                ms_project_app.FileClose()
        except Exception as close_error:
            print(f"An error occurred while closing the project: {close_error}")

if __name__ == "__main__":
    # Replace 'your_project_file.mpp' with the actual path to your Microsoft Project file
    project_file_path = 'GreenwoodIN.mpp'
    
    try:
        list_task_attributes(project_file_path)
    except Exception as e:
        print(f"An error occurred: {e}")
Get this error:

Error:
An error occurred: (-2147352567, 'Exception occurred.', (1004, '', 'Project cannot open the file.', 'C:\\Program Files\\Microsoft Office\\root\\Office16\\VBAPJ.CHM\x00', 131072, 0), None)
I can open the file manually from the folder its located in and no issues, but not within python.. I will say that executing the above, will create an instance of MS Project in my task manager.
Reply
#5
Don't do this:
if __name__ == "__main__":
    # Replace 'your_project_file.mpp' with the actual path to your Microsoft Project file
    project_file_path = 'GreenwoodIN.mpp'
     
    try:
        list_task_attributes(project_file_path)
    except Exception as e:
        print(f"An error occurred: {e}")
Do this:
if __name__ == "__main__":
    # Replace 'your_project_file.mpp' with the actual path to your Microsoft Project file
    project_file_path = 'GreenwoodIN.mpp'
    list_task_attributes(project_file_path)
Only use try/except when you do something useful with the exception information. Your code succeeds at hiding information that might help understand the problem.
Reply
#6
So are you saying that instead of this:

project_file_path = 'GreenwoodIN.mpp'
Do this?
project_file_path = 'c:/GreenwoodIN.mpp'
Reply
#7
Disregard the above, that is correct, i added the full path and it started looping thru tasks.. but would thru an error occasionally with each task, so the loop would return a task, error, then next task and so on.
Reply
#8
The following works and returns the information i am looking for

import win32com.client

from datetime import datetime

from dateutil.relativedelta import relativedelta, SA

def get_saturday_of_current_week():
    today = datetime.now().date()
    saturday_of_current_week = today + relativedelta(weekday=SA(+1))
    return saturday_of_current_week

def list_task_attributes(file_path):
    ms_project_app = None
    try:
        # Create an instance of the Microsoft Project application
        ms_project_app = win32com.client.Dispatch("MSProject.Application")

        # Open the Microsoft Project file in read-only mode
        ms_project_app.FileOpen(file_path, ReadOnly=True)

        # Get Saturday of the current week
        saturday_of_current_week = get_saturday_of_current_week()

        # Access all tasks and print information for tasks not 100 percent complete
        for task in ms_project_app.ActiveProject.Tasks:
            if task.PercentComplete < 100 and task.Finish.date() < saturday_of_current_week:
                print(f"\nTask: {task.ID}")
                print(f"Task Name: {task.Name}")
                print(f"Start Date: {task.Start}")
                print(f"Finish Date: {task.Finish}")
                print(f"Resource Name: {task.ResourceNames}")
                print(f"% Complete: {task.PercentComplete}")

    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        try:
            # Close the Microsoft Project file only if it's open
            if ms_project_app and ms_project_app.ActiveProject:
                ms_project_app.FileClose()
        except Exception as close_error:
            print(f"An error occurred while closing the project: {close_error}")

if __name__ == "__main__":
    # Replace 'your_project_file.mpp' with the actual path to your Microsoft Project file
    project_file_path = r'C:\VS Projects\MS Project Scripts\GreenwoodIN.mpp'
    list_task_attributes(project_file_path)  
Reply
#9
I asked you to remove the code that catches the exception and let Python provide a detailed error report. try/except get in the way during debugging, especially when you are in the "learning how to use a new tool" stage of development. The error message returned was useless and gave no indication that the problem was you provided a bad path.

Glad it is working now.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why can't it extract the data from .txt well? Melcu54 3 683 Aug-20-2023, 10:07 PM
Last Post: deanhystad
Question Need help for a python script to extract information from a list of files lephunghien 6 1,110 Jun-12-2023, 05:40 PM
Last Post: snippsat
  script to calculate data in csv-files ledgreve 0 1,111 May-19-2023, 07:24 AM
Last Post: ledgreve
  python Extract sql data by combining below code. mg24 1 971 Oct-03-2022, 10:25 AM
Last Post: mg24
  SQL Alchemy help to extract sql data into csv files mg24 1 1,793 Sep-30-2022, 04:43 PM
Last Post: Larz60+
  How to extract specific data from .SRC (note pad file) Shinny_Shin 2 1,284 Jul-27-2022, 12:31 PM
Last Post: Larz60+
  Apply textual data cleaning to several CSV files ErcoleL99 0 845 Jul-09-2022, 03:01 PM
Last Post: ErcoleL99
  Extract parts of multiple log-files and put it in a dataframe hasiro 4 2,098 Apr-27-2022, 12:44 PM
Last Post: hasiro
  How to rotate bits ? korenron 2 1,640 Mar-23-2022, 04:05 PM
Last Post: Larz60+
  Can ZipFile be used to extract hidden files? AiedailEclipsed 0 1,637 Mar-22-2022, 05:21 PM
Last Post: AiedailEclipsed

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020