所需设置
在工程中增加引用Microsoft Project 11.0 Object Library,该引用在com选项卡中。
注意
Microsoft Project 11.0 Object Library是本机安装Microsoft Project以后才能引用的。
如果引用之后运行程序报错:
检索 COM 类工厂中 CLSID 为 {…………} 的组件时失败,原因是出现以下错误: …………。
请在控制面板-》管理工具-》组件服务-》计算机-》我的电脑-》DCom配置-》找到Microsoft Project Basic
之后单击属性打开此应用程序的属性对话框,单击"安全"选项卡,分别在"启动和激活权限"和"访问权限"组中选中"自定义"。
using System; using System.Collections.Generic; using System.Text; using Microsoft.Office.Interop.MSProject; namespace ConsoleApplication { class Program { static void Main(string[] args) { Program pro = new Program(); pro.readMpp(); // pro.callMacro(); //pro.createMpp(); } //调用mpp中定义的宏 public void callMacro() { Object missing = Type.Missing; ApplicationClass prj = new ApplicationClass(); //打开mpp文件 prj.FileOpen("C:/Documents and Settings/Administrator/My Documents/test.mpp", false, missing, missing, missing, missing, missing, missing, missing, missing, missing, PjPoolOpen.pjPoolReadWrite, missing, missing, missing, missing); //调用名称为testMacro prj.Macro("testMacro"); //关闭,但不保存mpp prj.FileClose(PjSaveType.pjDoNotSave, false); prj.Quit(PjSaveType.pjDoNotSave); } public void readMpp() { Object missing = Type.Missing; ApplicationClass prj = new ApplicationClass(); prj.FileOpen("D:/test.mpp", false, missing, missing, missing, missing, missing, missing, missing, missing, missing, PjPoolOpen.pjPoolReadWrite, missing, missing, missing, missing); foreach (Project proj in prj.Projects) { foreach (Task task in proj.Tasks) { System.Console.WriteLine("|" + task.Name + "|" + task.UniqueID + "|" + task.ResourceNames + "|"); } } prj.FileClose(PjSaveType.pjSave, false); prj.Quit(PjSaveType.pjSave); System.Console.Read(); } public void createMpp() { Object missing = Type.Missing; ApplicationClass prj = new ApplicationClass(); PjFileFormat format = PjFileFormat.pjMPP;//format定义 prj.Visible = true; prj.FileNew(Type.Missing, Type.Missing, Type.Missing, false); Project myProject = prj.ActiveProject; Task task = null; task = myProject.Tasks.Add("zhi", 1); task.Start = "2008-8-1"; task.Finish = "2008-8-18"; task.SetField(PjField.pjTaskNotes, "Task1"); task = null; task = myProject.Tasks.Add("wenzhixing", 2); task.Start = "2008-8-8"; task.Finish = "2008-8-28"; task.ActualStart = "2008-9-8 8:00"; task.ActualFinish = "2008-9-28 17:00"; task.OutlineLevel = 2; task.SetField(PjField.pjTaskResourceNames, "wenzhi"); task = null; task = myProject.Tasks.Add("wen", 3); task.Start = "2008-8-11"; task.Finish = "2008-8-18"; task.SetField(PjField.pjTaskNotes, "Task2"); task.Notes += "hehe"; task.OutlineLevel = 1; task = null; task = myProject.Tasks.Add("wen", 4); task.Start = "2008-8-18"; task.Finish = "2008-8-28"; task.OutlineLevel = 2; task.SetField(PjField.pjTaskResourceNames, "wenzhi"); prj.FileSaveAs("C:/Documents and Settings/Administrator/My Documents/mjm.mpp", format, missing, false, missing, missing, missing, missing, missing, missing, PjPoolOpen.pjPoolReadWrite, missing, missing, missing, missing, missing, missing, missing, missing); } } }