工程管理mpp导入导出解决方案

来源:互联网 发布:js整型 编辑:程序博客网 时间:2024/05/23 21:12

   前不久,刚实习,遇到的项目是工程类的,其中要实现的功能是甘特图的导入和导出。到网上找了很久,没有好的解决方案,就自己做了一个。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Microsoft.Office.Interop.MSProject;
using System.IO;
using com.jwsoft.pm.data;
using Microsoft.Office;

public partial  class projectImport : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    /// <summary>
    /// 导入数据
    /// </summary>
    /// <param name="fileName"></param>
    private void GetIMP(string fileName)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("选择", Type.GetType("System.Boolean"));
        dt.Columns.Add("wbs", Type.GetType("System.String"));
        dt.Columns.Add("taskcode", Type.GetType("System.String"));
        dt.Columns.Add("任务名称", Type.GetType("System.String"));
        //dt.Columns.Add("优先级", Type.GetType("System.String"));task.Priority,
        dt.Columns.Add("开始时间", Type.GetType("System.DateTime"));
        dt.Columns.Add("结束时间", Type.GetType("System.DateTime"));
        dt.Columns.Add("完成百分比", Type.GetType("System.String"));
        //dt.Columns.Add("是否完成", Type.GetType("System.String"));task.ActualFinish,
        dt.Columns.Add("前置任务", Type.GetType("System.String"));
        dt.Columns.Add("孩子个数", Type.GetType("System.Int32"));
        dt.Columns.Add("父节点", Type.GetType("System.String"));
        try
        {
            Microsoft.Office.Interop.MSProject.ApplicationClass prj = new ApplicationClass();
            string filename = fileName;
            prj.FileOpen(filename, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.MSProject.PjPoolOpen.pjPoolReadOnly, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            foreach (Microsoft.Office.Interop.MSProject.Project proj in prj.Projects)
            {
              
                foreach (Microsoft.Office.Interop.MSProject.Task task in proj.Tasks)
                {
                    if (task != null)
                    {
                        int taskLive = task.OutlineLevel;//表示该节点的级别
                        Tasks tasks = task.OutlineChildren;
                        int count = tasks.Count;
                        string para = "";
                        if (taskLive != 1)
                        {
                            para = task.OutlineParent.WBS.ToString();
                        }

                        string predecessorTasks = "";
                        //foreach (Task t in task.PredecessorTasks)
                        //{
                        //    predecessorTasks = t.Predecessors;
                        //}
                      
                        dt.Rows.Add(new object[] { true, task.WBS, GetTaskCode(task.WBS), task.Name, task.Start.ToString(), task.Finish.ToString(), task.PercentComplete, predecessorTasks, count, GetTaskCode(para) });

                    }
                }
            }
            GV_IMP.DataSource = dt;
            GV_IMP.DataBind();


            prj.FileCloseAll(PjSaveType.pjDoNotSave);
            prj.Quit(PjSaveType.pjDoNotSave);
        }
        catch (System.Exception e)
        {
            Response.Write("<script>alert('出错')</script>");
        }
    }
    /// <summary>
    /// 选择文件源
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        string filename = FileUpload1.PostedFile.FileName;
        GetIMP(filename);
    }

    public static string GetTaskCode(string node)
    {
        string[] item = node.Split('.');//分割传进来的字符串
        string parentNode = "";              //存储新的节点值
        for (int i = 0; i < item.Length; i++)
        {
            parentNode += item[i].PadLeft(3, '0');
            if (parentNode == "000")
            {
                return "";
            }
        }
        return parentNode;
    }
    /// <summary>
    /// 导入到数据库
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button2_Click(object sender, EventArgs e)
    {

    }
    /// <summary>
    /// 导出文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button3_Click(object sender, EventArgs e)
    {
        object Create = true;

 


        Microsoft.Office.Interop.MSProject.ApplicationClass prj = new Microsoft.Office.Interop.MSProject.ApplicationClass();
        prj.Visible = true;

 

        //string path = Server.MapPath("Temp2003.mpp");
       prj.FileNew(Type.Missing,Type.Missing, Type.Missing,false);
        //prj.FileNew(Type.Missing, Type.Missing, Type.Missing, false);
        Microsoft.Office.Interop.MSProject.PjSaveType savechage = Microsoft.Office.Interop.MSProject.PjSaveType.pjPromptSave;//此为保存  
        Microsoft.Office.Interop.MSProject.Project myProject = prj.ActiveProject;
        Microsoft.Office.Interop.MSProject.PjFileFormat format = Microsoft.Office.Interop.MSProject.PjFileFormat.pjMPP;//format定义
       // PjField pj=Microsoft.Office.Interop.MSProject.PjField.pjTaskText1;
        object missing = System.Reflection.Missing.Value;//missing值 
        myProject.AutoTrack = true;


        myProject.HoursPerDay = 8;
        myProject.HoursPerWeek = 56;
        myProject.DaysPerMonth =30;
        Microsoft.Office.Interop.MSProject.WeekDays weedday = myProject.Calendar.WeekDays;
        weedday[1].set_Working(true);
        weedday[7].set_Working(true);

       
        //prj.CustomFieldIndicatorAdd(PjCustomField.pjCustomProjectEnterpriseFlag1,);
       // prj.CustomizeField();
       
        myProject.ShowCriticalSlack = 0;
      
        Microsoft.Office.Interop.MSProject.Task task = null;
        DataTable dt = GetAll();

        //prj.Application.CustomFieldRename(PjCustomField.pjCustomTaskText1, "bb", Create);

 

        //prj.CustomFieldIndicatorAdd(PjCustomField.pjCustomTaskText1, PjComparison.pjCompareAnyValue, "ss", PjIndicator.pjIndicatorPlusYellow, PjCriteriaList.pjCriteriaProjectSummary, 2);
       // prj.Alerts(true);
       // prj.AppMaximize();
       // prj.BoxProgressMarksShow(true);
       
        int i = 1;
        foreach (DataRow dr in dt.Rows)
        {
           
            task = null;
          
            task = myProject.Tasks.Add(dr["TaskName"], i++);

         
           string start = dr["StartDateP"].ToString();
            task.Start = start;
            task.Finish = dr["EndDateP"];
            task.Milestone = dr["IsMTask"].ToString() == "1" ? true : false;//是否里程碑:0=否、1=是
            task.OutlineLevel = (short)(dr["TaskCode"].ToString().Length / 3);
            //task.WBS = replace(dr["TaskCode"].ToString());
            task.SetField(Microsoft.Office.Interop.MSProject.PjField.pjTaskText1, "Taska");
           // task.r
            task.Text1 = "fff";

            task.Rollup = true;
        }
        //prj.ViewShowWork();
        //prj.OfficeOnTheWeb();
        //prj.ObjectConvert();

        string filename = Server.MapPath("test.mpp");
        prj.FileSaveAs(filename, format, missing, missing, missing, missing, missing, missing,missing, "MSProject.mpp.9", missing, missing, missing, missing, missing, missing, missing, missing, missing);
       prj.Quit(savechage);
    }
    //获得说有数据
    public DataTable GetAll()
    {
        string sql = "SELECT *  FROM [pm_PlanDetailWbs_History] where planid=1840 order by TaskCode";
        return publicDbOpClass.DataTableQuary(sql);
    }
    //换算wbs 001001
    public string replace(string taskcode)
    {
        string result = "";
        for (int i = 0; i < taskcode.Length / 3; i++)
        {
            string a = taskcode.Substring(i * 3, 3);
            result += Convert.ToInt32(a) + ".";
        }
        result = result.TrimEnd('.');
        return result;
    }
    protected void Button4_Click(object sender, EventArgs e)
    {
        //response.addHeader("Content-Disposition", "attachment; filename=" + response.encodeURL(downloadfile)); 
        //Response.AddHeader("Content-Disposition", "attachment; filename=test.mpp");
        string path = "test.mpp";

        System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(path));
        Response.Clear();
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        //   添加头信息,为"文件下载/另存为"对话框指定默认文件名  
        Response.AddHeader("Content-Disposition", "attachment;   filename=test.abc" );
        //   添加头信息,指定文件大小,让浏览器能够显示下载进度  
        Response.AddHeader("Content-Length", file.Length.ToString());

        //   指定返回的是一个不能被客户端读取的流,必须被下载  
        Response.ContentType = "application/abc";

        //   把文件流发送到客户端  
        Response.WriteFile(file.FullName);
        //   停止页面的执行  

        Response.End();
        

    }
}

 

原创粉丝点击