设为首页收藏本站

最大的系统仿真与系统优化公益交流社区

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 3747|回复: 0

how to Import model from Excel (Simio API)

    [复制链接]
发表于 2012-9-9 10:17:02 | 显示全部楼层 |阅读模式
本帖最后由 rwj_238 于 2012-9-9 10:30 编辑

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using SimioAPI;
using SimioAPI.Extensions;

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace ImportObjectsAndLinksFromSpreadsheetAddIn
{
    public class ImportObjectsAndLinksFromSpreadsheetAddIn : IDesignAddIn
    {
        #region IDesignAddIn Members

        /// <summary>
        /// Property returning the name of the add-in. This name may contain any characters and is used as the display name for the add-in in the UI.
        /// </summary>
        public string Name
        {
            get { return "Load objects and links from an external spreadsheet"; }
        }

        /// <summary>
        /// Property returning a short description of what the add-in does.  
        /// </summary>
        public string Description
        {
            get { return "This addin loads objects and links into a model from an external spreadsheet"; }
        }
        
        /// <summary>
        /// Property returning an icon to display for the add-in in the UI.
        /// </summary>
        public Image Icon
        {
            get { return Properties.Resources.Icon; }
        }

        #endregion

         /// <summary>
        /// Method called when the add-in is run.
        /// </summary>
        public void Execute(IDesignContext context)
        {
            // Check to make sure a model has been opened in Simio
            if (context.ActiveModel == null)
            {
                MessageBox.Show("You must have an active model to run this add-in.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
         
            // Open the file.  Return immediately if the user cancels the file open dialog
            var getFile = new OpenFileDialog();
            getFile.Filter = "Excel Files(*.xlsx)|*.xlsx";
            if (getFile.ShowDialog() == DialogResult.Cancel)
            {
                MessageBox.Show("Canceled by user.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
                     
            //Open Status Window
            StatusWindow statWin = new StatusWindow("Importing From Excel Spreadsheet");
            statWin.Show();
            // Update Status Window
            statWin.UpdateProgress(25);

            //Start Excel Application object.
            var xlApp = new Excel.Application();

                    //Get a new workbook.
            var xlWorkBook = (Excel._Workbook)(xlApp.Workbooks.Open(getFile.FileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0));
            
            // Create the log message list
            List<String> logMessages = new List<String>();

            // Create the node and link sheet lists
            List<Excel.Worksheet> objectsWorksheets = new List<Excel.Worksheet>();
            List<Excel.Worksheet> linksWorksheets = new List<Excel.Worksheet>();

            // Look through every sheet
            foreach (Excel.Worksheet ws in xlWorkBook.Worksheets)
            {
               if (ws.Name.Length >= 5)
              {
                  // Add any sheet that name starts with 'objects' to the objects list
                  if (ws.Name.Length >= 7 && String.Compare(ws.Name.Substring(0, 7), "Objects") == 0)
                  {
                      objectsWorksheets.Add(ws);
                  }
                  // Add any sheet that name starts with 'link' to the link list
                  else if (String.Compare(ws.Name.Substring(0, 5), "Links") == 0)
                  {
                      linksWorksheets.Add(ws);
                  }
              }
            }

            if (objectsWorksheets.Count + linksWorksheets.Count == 0)
            {
                MessageBox.Show("Workbook contains no valid object or link worksheets.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // Update Status Window
            statWin.UpdateProgress(50);
               
            // get intelligent objects
            var intellObjects = context.ActiveModel.Facility.IntelligentObjects;

            // Read and create the objects.
            int addedCount;
            int updatedCount;
            foreach (Excel.Worksheet oWS in objectsWorksheets)
            {
                var usedRange = (Excel.Range)oWS.UsedRange;
                if (usedRange.Rows.Count > 0)
                {
                    logMessages.Add(string.Format("Reading {0} rows from sheet {1}", usedRange.Rows.Count -1, oWS.Name));
                }
                addedCount = 0;
                updatedCount = 0;
              
              for (int rowIndex = 2; rowIndex <= usedRange.Rows.Count; rowIndex++)
              {
                  var row = (Excel.Range)usedRange.Rows[rowIndex];
                  var cell = (Excel.Range)row.Cells[1];

                  if (cell.Value == null)
                  {
                      DialogResult dr = MessageBox.Show(string.Format("Error reading cell 1 on row number {0} of sheet {1}", rowIndex.ToString(), oWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                      if (dr == DialogResult.OK) continue;
                      else
                      {
                          statWin.Close();
                          return;
                      }
                  }
                  string className = cell.Value.ToString();
                  
                  cell = row.Cells[2];
                  if (cell.Value == null)
                  {
                      DialogResult dr = MessageBox.Show(string.Format("Error reading cell 2 on row number {0} of sheet {1}", rowIndex.ToString(), oWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                      if (dr == DialogResult.OK) continue;
                      else
                      {
                          statWin.Close();
                          return;
                      }
                  }
                  string itemName = cell.Value.ToString();

                  // Find the coordinates for the object
                  double x = 0.0, y = 0.0, z = 0.0;

                  if (row.Cells[3].Value == null || !Double.TryParse(row.Cells[3].Value.ToString(), out x))
                  {
                      DialogResult dr = MessageBox.Show(string.Format("Error reading cell x on row number {0} of sheet {1}", rowIndex.ToString(), oWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                      if (dr == DialogResult.Cancel)
                      {
                          statWin.Close();
                          return;
                      }
                  }
                  if (row.Cells[4].Value == null || !Double.TryParse(row.Cells[4].Value.ToString(), out y))
                  {
                      DialogResult dr = MessageBox.Show(string.Format("Error reading cell y on row number {0} of sheet {1}", rowIndex.ToString(), oWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                      if (dr == DialogResult.Cancel)
                      {
                          statWin.Close();
                          return;
                      }
                  }

                  if (row.Cells[5].Value == null || !Double.TryParse(row.Cells[5].Value.ToString(), out z))
                  {
                     DialogResult dr = MessageBox.Show(string.Format("Error reading z on row number {0} of sheet {1}", rowIndex.ToString(), oWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                     if (dr == DialogResult.Cancel)
                     {
                         statWin.Close();
                         return;
                     };
                  }

                  // Add the coordinates to the intelligent object
                  FacilityLocation loc = new FacilityLocation(x, y, z);
                  var intellObj = intellObjects[itemName];
                  if (intellObj == null)
                  {
                      intellObj = intellObjects.CreateObject(className, loc);
                      if (intellObj == null)
                      {
                          DialogResult dr = MessageBox.Show(string.Format("Error creating object on row number {0} of sheet {1}...Object class might not exist in model", rowIndex.ToString(), oWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                          if (dr == DialogResult.OK) continue;
                          else
                          {
                              statWin.Close();
                              return;
                          }
                      }
                      intellObj.ObjectName = itemName;
                      addedCount++;
                  }
                  else
                  {
                      // update coords of existing one.
                      intellObj.Location = loc;
                      updatedCount++;
                  }

                  // get header row on sheet
                  var headerRow = usedRange.Rows[1];

                  // update properties on object
                  for (int colIndex = 6; colIndex <= usedRange.Columns.Count; colIndex++)
                  {
                      var headerCell = headerRow.Cells[colIndex];
                      foreach (IProperty prop in intellObj.Properties)
                      {
                          if (headerCell.Value != null)
                          {
                              if (headerCell.Value.ToString() == prop.Name)
                              {
                                  cell = row.Cells[colIndex];
                                  if (cell.Value != null)
                                  {
                                      prop.Value = cell.Value.ToString();
                                  }
                              }
                          }
                      }
                  }
              }
              logMessages.Add(string.Format("Added {0} objects and updated {1} objects", addedCount.ToString(), updatedCount.ToString()));
            }

            // Update Status Window
            statWin.UpdateProgress(75);

            // Read and create the links.
            foreach (Excel.Worksheet lWS in linksWorksheets)
            {
                var usedRange = (Excel.Range)lWS.UsedRange;
                if (usedRange.Rows.Count > 0)
                {
                    logMessages.Add(string.Format("Reading {0} rows from sheet {1}", usedRange.Rows.Count -1, lWS.Name));
                }
                addedCount = 0;
                updatedCount = 0;
              
              for (int rowIndex = 2; rowIndex <= usedRange.Rows.Count; rowIndex++)
              {
                var row = (Excel.Range)lWS.Rows[rowIndex];
                var cell = (Excel.Range)row.Cells[1];
                if (cell.Value == null)
                {
                    DialogResult dr = MessageBox.Show(string.Format("Error reading cell 1 on row number {0} of sheet {1}", rowIndex.ToString(), lWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                    if (dr == DialogResult.OK) continue;
                    else
                    {
                        statWin.Close();
                        return;
                    }
                }
                string className = cell.Value.ToString();

                cell = (Excel.Range)row.Cells[2];
                if (cell.Value == null)
                {
                    DialogResult dr = MessageBox.Show(string.Format("Error reading cell 2 on row number {0} of sheet {1}", rowIndex.ToString(), lWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                    if (dr == DialogResult.OK) continue;
                    else
                    {
                        statWin.Close();
                        return;
                    }
                }
                string linkName = cell.Value.ToString();

                cell = (Excel.Range)row.Cells[3];
                if (cell.Value == null)
                {
                    DialogResult dr = MessageBox.Show(string.Format("Error reading cell 3 on row number {0} of sheet {1}", rowIndex.ToString(), lWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error); ;
                    if (dr == DialogResult.OK) continue;
                    else
                    {
                        statWin.Close();
                        return;
                    }
                }
                string fromNodeName = cell.Value.ToString();

                cell = (Excel.Range)row.Cells[4];
                if (cell.Value == null)
                {
                    DialogResult dr = MessageBox.Show(string.Format("Error reading cell 4 on row number {0} of sheet {1}", rowIndex.ToString(), lWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                    if (dr == DialogResult.OK) continue;
                    else
                    {
                        statWin.Close();
                        return;
                    }
                }
                string toNodeName = cell.Value.ToString();

                var fromNode = intellObjects[fromNodeName] as INodeObject;
                if (fromNode == null)
                {
                    DialogResult dr = MessageBox.Show(string.Format("Error finding from node name {0} on row number {1} of sheet {2}", fromNodeName, rowIndex.ToString(), lWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                    if (dr == DialogResult.OK) continue;
                    else
                    {
                        statWin.Close();
                        return;
                    }
                }

                var toNode = intellObjects[toNodeName] as INodeObject;
                if (toNode == null)
                {
                    DialogResult dr = MessageBox.Show(string.Format("Error reading to node name {0} on row number {1} of sheet {2}", toNodeName, rowIndex.ToString(), lWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                    if (dr == DialogResult.OK) continue;
                    else
                    {
                        statWin.Close();
                        return;
                    }
                }

                var link = intellObjects[linkName];
                if (link == null)
                {
                    // Find the coordinates for the vertex
                    double x = double.MinValue, y = double.MinValue, z = double.MinValue;
                    if (row.Cells[5].Value != null)
                    {
                        if (!Double.TryParse(row.Cells[5].Value.ToString(), out x))
                        {
                            DialogResult dr = MessageBox.Show(string.Format("Error reading cell x on row number {0} of sheet {1}", rowIndex.ToString(), lWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                            if (dr == DialogResult.OK) continue;
                            else
                            {
                                statWin.Close();
                                return;
                            }
                        }
                    }
                    if (row.Cells[6].Value != null)
                    {
                        if (!Double.TryParse(row.Cells[6].Value.ToString(), out y))
                        {
                            DialogResult dr = MessageBox.Show(string.Format("Error reading cell y on row number {0} of sheet {1}", rowIndex.ToString(), lWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                            if (dr == DialogResult.OK) continue;
                            else
                            {
                                statWin.Close();
                                return;
                            }
                        }
                    }
                    if (row.Cells[7].Value != null)
                    {
                        if (!Double.TryParse(row.Cells[7].Value.ToString(), out z))
                        {
                            DialogResult dr = MessageBox.Show(string.Format("Error reading cell z on row number {0} of sheet {1}", rowIndex.ToString(), lWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                            if (dr == DialogResult.OK) continue;
                            else
                            {
                                statWin.Close();
                                return;
                            }
                        }
                    }

                    // Define List of Facility Locatoins
                    List<FacilityLocation> locs = new List<FacilityLocation>();      
            
                    // If coordinates are good, add vertex to facility locations
                    if (x > double.MinValue & z > double.MinValue & z > double.MinValue)
                    {
                        // Add the coordinates to the intelligent object
                        FacilityLocation loc = new FacilityLocation(x, y, z);
                        locs.Add(loc);
                    }                  

                    // Add Link
                    link = intellObjects.CreateLink(className, fromNode, toNode, locs);
                    if (link == null)
                    {
                        DialogResult dr = MessageBox.Show(string.Format("Error creating link from row number {0} of sheet {1}", fromNodeName, rowIndex.ToString(), lWS.Name), null, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                        if (dr == DialogResult.OK) continue;
                        else
                        {
                            statWin.Close();
                            return;
                        }
                    }
                    link.ObjectName = linkName;
                    addedCount++;
                }
                else
                {
                    updatedCount++;               
                }              

                // get header row on sheet
                var headerRow = (Excel.Range)usedRange.Rows[1];

                // update properties on object
                for (int colIndex = 8; colIndex <= usedRange.Columns.Count; colIndex++)
                {
                    var headerCell = headerRow.Cells[colIndex];
                    foreach (IProperty prop in link.Properties)
                    {
                        if (headerCell.Value != null)
                        {
                            if (headerCell.Value.ToString() == prop.Name)
                            {
                                cell = row.Cells[colIndex];
                                if (cell.Value != null)
                                {
                                    prop.Value = cell.Value.ToString();
                                }
                            }
                        }
                    }
                 }  
              }
              logMessages.Add(string.Format("Added {0} links and skipped {1} existing links", addedCount.ToString(), updatedCount.ToString()));
            }

            // Update Status Window
            statWin.UpdateProgress(100);

            //show log messages
            string msg = string.Join(System.Environment.NewLine, logMessages.ToArray());
            MessageBox.Show(msg, "ImportObjectsAndLinksFromSpreadsheetAddIn", MessageBoxButtons.OK, MessageBoxIcon.Information);
            statWin.Close();
        }     
    }
}

================================================
tjf,无锡江南大学

Simio,Next Generation Simulation
The official reseller/Dev. Support : Http://www.simio-china.com
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|Archiver|手机版|SimulWay 道于仿真   

GMT+8, 2024-4-29 06:57 , Processed in 0.013710 second(s), 14 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表