应用程序:PanelSchedule

Revit平台:MEP

Revit版本:2011.0

首次发布于:2011.0

编程语言:C

技能水平:初级

类别:数据交换

类型:ExternalCommand

主题:展示面板时间表API的工作原理。

概要:

本示例包含3个外部命令,演示如何使用面板时间表API

1. PanelScheduleExport - 通过API获取面板时间表视图数据,并生成CSV文件或HTML页面。

2. InstanceViewCreation - 为所选电气面板创建一个面板时间表视图实例。

3. SheetImport - 将面板时间表视图放置在工作表视图上。

类:

- Autodesk.Revit.DB.Electrical.PanelScheduleView

- Autodesk.Revit.DB.Electrical.PanelScheduleSheetInstance

- Autodesk.Revit.DB.SectionType

- Autodesk.Revit.DB.TableSectionData

项目文件:

- CSVTranslator.cs

它包含了CSVTranslator类,负责将来自Revit的面板时间表视图数据转换为.CSV格式。

- HTMLTranslator.cs

它包含了HTMLTranslator类,负责将来自Revit的面板时间表视图数据转换为HTML表格。

- InstanceViewCreation.cs

它包含了InstanceViewCreation类,演示了如何使用PanelSceduleView.CreateInstanceView API为电气面板创建面板时间表。

- SheetImport.cs

它包含了SheetImport类,演示了如何将面板时间表视图(使用PanelScheduleSheetInstance)放置在工作表视图上。

描述:

功能:

- Revit面板时间表视图导出为HTML页面。

- 为您选择的电气面板创建一个面板时间表视图。

- 将面板时间表视图放置在工作表视图中。

 

实现:

命令PanelScheduleExport

- 通过ElementClassFilter获取所有PanelScheduleView实例。

- 忽略作为模板的PanelScheduleView实例。

- 通过API PanelScheduleView.GetCellText(sectionType, ii, jj)获取所有表单单元格。

- 将表格导出到HTML或逗号分隔格式的“table”节点中。

命令InstanceViewCreation

- 通过Selection.PickObject(ObjectType.Element)获取一个电气面板。

- 通过PanelScheduleView.CreateInstanceView(doc, selectedPanel.Element.Id)创建面板视图。

命令SheetImport

- 通过doc.ActiveView获取一个工作表视图。

- 通过PanelScheduleSheetInstance.Create(doc, psView.Id, sheet)将面板时间表视图放置在工作表视图中。

说明:

命令PanelScheduleExport

1. 运行Revit MEP 2011

2. 确保“template.html”文件与外部命令程序集位于同一文件夹中。

3. 运行此外部命令。

4. 它将为Revit文档中的每个面板时间表视图实例生成一个CSV文件或HTML页。

 

命令InstanceViewCreation

1. 运行Revit MEP 2011

2. 切换到包含一个电气面板的视图。

3. 运行此外部命令。

4. 选择一个电气面板。

5. 它将为您选择的电气面板创建一个面板视图。

 

命令SheetImport

1. 运行Revit MEP 2011

2. 创建或打开一个工作表视图。

3. 运行此外部命令。

4. 它将在工作表视图中放置面板时间表视图。

源代码

完整的源代码请加入QQ群649037449,在群文件中下载RevitSDK.exe,解压后在文件夹中搜索本文中应用程序名称即可获得完整源码

CSVTranslator.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//

using System;
using System.IO;
using System.Text;

using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;

namespace Revit.SDK.Samples.PanelSchedule.CS
{
    /// <summary>
    /// Translate the panel schedule view data from Revit to CSV.
    /// </summary>
    class CSVTranslator : Translator
    {
        /// <summary>
        /// create a CSVTranslator instance for a PanelScheduleView instance.
        /// </summary>
        /// <param name="psView">the exporting panel schedule view instance.</param>
        public CSVTranslator(PanelScheduleView psView)
        {
            m_psView = psView;
        }

        /// <summary>
        /// export to a CSV file that contains the PanelScheduleView instance data.
        /// </summary>
        /// <returns>the exported file path</returns>
        public override string Export()
        {
            string asemblyName = System.Reflection.Assembly.GetExecutingAssembly().Location;

            string panelScheduleCSVFile = asemblyName.Replace("PanelSchedule.dll", ReplaceIllegalCharacters(m_psView.Name) + ".csv");

            if (File.Exists(panelScheduleCSVFile))
            {
                File.Delete(panelScheduleCSVFile);
            }

            using (StreamWriter sw = File.CreateText(panelScheduleCSVFile))
            {
                //sw.WriteLine("This is my file.");
                DumpPanelScheduleData(sw);
                sw.Close();
            }

            return panelScheduleCSVFile;
        }

        /// <summary>
        /// dump PanelScheduleData to comma delimited.
        /// </summary>
        /// <param name="sw"></param>
        private void DumpPanelScheduleData(StreamWriter sw)
        {
            DumpSectionData(sw, m_psView, SectionType.Header);
            DumpSectionData(sw, m_psView, SectionType.Body);
            DumpSectionData(sw, m_psView, SectionType.Summary);
            DumpSectionData(sw, m_psView, SectionType.Footer);
        }

        /// <summary>
        /// dump SectionData to comma delimited.
        /// </summary>
        /// <param name="sw">exporting file stream</param>
        /// <param name="psView">the PanelScheduleView instance is exporting.</param>
        /// <param name="sectionType">which section is exporting, it can be Header, Body, Summary or Footer.</param>
        private void DumpSectionData(StreamWriter sw, PanelScheduleView psView, SectionType sectionType)
        {
            int nRows_Section = 0;
            int nCols_Section = 0;
            getNumberOfRowsAndColumns(m_psView.Document, m_psView, sectionType, ref nRows_Section, ref nCols_Section);

            for (int ii = 0; ii < nRows_Section; ++ii)
            {
                StringBuilder oneRow = new StringBuilder();
                for (int jj = 0; jj < nCols_Section; ++jj)
                {
                    try
                    {
                        oneRow.AppendFormat("{0},", m_psView.GetCellText(sectionType, ii, jj));
                    }
                    catch (Exception)
                    {
                        // do nothing.
                    }
                }

                sw.WriteLine(oneRow.ToString());
            }
        }
    }
}

HTMLTranslator.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//

using System;
using System.Xml;

using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.UI;

namespace Revit.SDK.Samples.PanelSchedule.CS
{
    /// <summary>
    /// Translate the panel schedule view data from Revit to HTML table.
    /// </summary>
    class HTMLTranslator : Translator
    {   
        /// <summary>
        /// create a Translator instance for a PanelScheduleView instance.
        /// </summary>
        /// <param name="psView">the exporting panel schedule view instance.</param>
        public HTMLTranslator(PanelScheduleView psView)
        {
            m_psView = psView;
        }

        /// <summary>
        /// export to a HTML page that contains the PanelScheduleView instance data.
        /// </summary>
        /// <returns>the exported file path</returns>
        public override string Export()
        {
            string asemblyName = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string tempFile = asemblyName.Replace("PanelSchedule.dll", "template.html");

            if (!System.IO.File.Exists(tempFile))
            {
                TaskDialog messageDlg = new TaskDialog("Warnning Message");
                messageDlg.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
                messageDlg.MainContent = "Can not find 'template.html', please make sure the 'template.html' file is in the same folder as the external command assembly.";
                messageDlg.Show();
                return null;
            }
            

            string panelScheduleFile = asemblyName.Replace("PanelSchedule.dll", ReplaceIllegalCharacters(m_psView.Name) + ".html");

            XmlDocument doc = new XmlDocument();
            XmlTextWriter tw = new XmlTextWriter(panelScheduleFile, null);
            doc.Load(tempFile);

            XmlNode psTable = doc.DocumentElement.SelectSingleNode("//div/table[1]");
            DumpPanelScheduleData(psTable, doc);
            
            doc.Save(tw);

            return panelScheduleFile;
        }

        /// <summary>
        /// dump PanelScheduleData to a 'table' node in HTML.
        /// </summary>
        /// <param name="panelScheduleDataNode">a 'table' node in HTML.</param>
        /// <param name="doc"></param>
        private void DumpPanelScheduleData(XmlNode panelScheduleDataNode, XmlDocument doc)
        {
            DumpSectionData(panelScheduleDataNode, doc, m_psView, SectionType.Header);
            DumpSectionData(panelScheduleDataNode, doc, m_psView, SectionType.Body);
            DumpSectionData(panelScheduleDataNode, doc, m_psView, SectionType.Summary);
            DumpSectionData(panelScheduleDataNode, doc, m_psView, SectionType.Footer);
        }

        /// <summary>
        /// dump SectionData to the 'tr' nodes in HTML. 
        /// </summary>
        /// <param name="panelScheduleDataNode">a 'table' node in HTML.</param>
        /// <param name="doc">HTML page</param>
        /// <param name="psView">the PanelScheduleView instance is exporting.</param>
        /// <param name="sectionType">which section is exporting, it can be Header, Body, Summary or Footer.</param>
        private void DumpSectionData(XmlNode panelScheduleDataNode, XmlDocument doc, PanelScheduleView psView, SectionType sectionType)
        {
            int nRows_Section = 0;
            int nCols_Section = 0;
            getNumberOfRowsAndColumns(m_psView.Document, m_psView, sectionType, ref nRows_Section, ref nCols_Section);

            for (int ii = 0; ii < nRows_Section; ++ii)
            {
                // add a <tr> node for each row
                XmlElement trNode = doc.CreateElement("tr");
                panelScheduleDataNode.AppendChild(trNode);

                for (int jj = 0; jj < nCols_Section; ++jj)
                {
                    // add <td> node for each cell
                    XmlElement tdNode = doc.CreateElement("td");

                    try
                    {
                        tdNode.InnerText = m_psView.GetCellText(sectionType, ii, jj);
                    }
                    catch (Exception)
                    {
                        // do nothing.
                    }

                    trNode.AppendChild(tdNode);
                }

            }
        }

    }
}

InstanceViewCreation.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//

using System;
using System.Collections.Generic;

using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;

namespace Revit.SDK.Samples.PanelSchedule.CS
{
    /// <summary>
    /// Create view instance for an electrical panel.
    /// </summary>
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
    public class InstanceViewCreation : IExternalCommand
    {
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application 
        /// which contains data related to the command, 
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application 
        /// which will be displayed if a failure or cancellation is returned by 
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application 
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command. 
        /// A result of Succeeded means that the API external method functioned as expected. 
        /// Cancelled can be used to signify that the user cancelled the external operation 
        /// at some point. Failure should be returned if the application is unable to proceed with 
        /// the operation.</returns>
        public virtual Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData
            , ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Autodesk.Revit.DB.Document doc = commandData.Application.ActiveUIDocument.Document;

            Reference selected = commandData.Application.ActiveUIDocument.Selection.PickObject(ObjectType.Element);

            Transaction newInstanceView = new Transaction(doc, "Create instance view for an electrical panel.");
            newInstanceView.Start();
            PanelScheduleView instanceView = PanelScheduleView.CreateInstanceView(doc, doc.GetElement(selected).Id);
            if (null == instanceView)
            {
                newInstanceView.RollBack();
                message = "Please select one electrical panel.";
                return Result.Failed;
            }
            else
            {
                newInstanceView.Commit();
                return Result.Succeeded;
            }

        }
    }
}

SheetImport.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//

using System;
using System.Collections.Generic;

using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.UI;

namespace Revit.SDK.Samples.PanelSchedule.CS
{
    /// <summary>
    /// Import the panel scheduel view to place on a sheet view.
    /// </summary>
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
    class SheetImport : IExternalCommand
    {
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application 
        /// which contains data related to the command, 
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application 
        /// which will be displayed if a failure or cancellation is returned by 
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application 
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command. 
        /// A result of Succeeded means that the API external method functioned as expected. 
        /// Cancelled can be used to signify that the user cancelled the external operation 
        /// at some point. Failure should be returned if the application is unable to proceed with 
        /// the operation.</returns>
        public virtual Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData
            , ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Autodesk.Revit.DB.Document doc = commandData.Application.ActiveUIDocument.Document;

            // get one sheet view to place panel schedule.
            ViewSheet sheet = doc.ActiveView as ViewSheet;
            if (null == sheet)
            {
                message = "please go to a sheet view.";
                return Result.Failed;
            }

            // get all PanelScheduleView instances in the Revit document.
            FilteredElementCollector fec = new FilteredElementCollector(doc);
            ElementClassFilter PanelScheduleViewsAreWanted = new ElementClassFilter(typeof(PanelScheduleView));
            fec.WherePasses(PanelScheduleViewsAreWanted);
            List<Element> psViews = fec.ToElements() as List<Element>;

            Transaction placePanelScheduleOnSheet = new Transaction(doc, "placePanelScheduleOnSheet");
            placePanelScheduleOnSheet.Start();

            XYZ nextOrigin = new XYZ(0.0, 0.0, 0.0);
            foreach (Element element in psViews)
            {
                PanelScheduleView psView = element as PanelScheduleView;
                if (psView.IsPanelScheduleTemplate())
                {
                    // ignore the PanelScheduleView instance which is a template.
                    continue;
                }

                PanelScheduleSheetInstance onSheet = PanelScheduleSheetInstance.Create(doc, psView.Id, sheet);
                onSheet.Origin = nextOrigin;
                BoundingBoxXYZ bbox = onSheet.get_BoundingBox(doc.ActiveView);
                double width = bbox.Max.X - bbox.Min.X;
                nextOrigin = new XYZ(onSheet.Origin.X + width, onSheet.Origin.Y, onSheet.Origin.Z);
            }

            placePanelScheduleOnSheet.Commit();

            return Result.Succeeded;

        }
    }
}