예제 #1
0
        public void InsertBom()
        {
            SldWorks       swApp     = default(SldWorks);
            ModelDoc2      swModel   = default(ModelDoc2);
            SelectionMgr   swSelMgr  = default(SelectionMgr);
            FeatureManager swFeatMgr = default(FeatureManager);

            SolidWorks.Interop.sldworks.View swView;
            BomTableAnnotation swBomAnn  = default(BomTableAnnotation);
            BomFeature         swBomFeat = default(BomFeature);
            long   anchorType            = 0;
            long   bomType       = 0;
            string configuration = null;
            string tableTemplate = null;

            object     visible = null;
            DrawingDoc swDraw;
            Sheet      swSheet = default(Sheet);

            //swApp = DirectCast(Marshal.GetActiveObject("SldWorks.Application"), SldWorks)
            swApp     = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            swModel   = swApp.ActiveDoc;
            swFeatMgr = swModel.FeatureManager;
            swDraw    = (DrawingDoc)swModel;
            swSheet   = swDraw.GetCurrentSheet();

            swModel.Extension.SetUserPreferenceString((int)swUserPreferenceStringValue_e.swDetailingLayer, (int)swUserPreferenceOption_e.swDetailingBillOfMaterial, "");
            //ecли FALSE вставляются все конфигурации
            swModel.Extension.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swOneConfigOnlyTopLevelBom, 0, false);

            swModel.Extension.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swBomTableDontAddQTYNextToConfigName, 0, true);
            swModel.Extension.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swDontCopyQTYColumnNameFromTemplate, 0, true);
            //swDraw.SetUserPreferenceIntegerValue(swBomTableZeroQuantityDisplay, swZeroQuantityBlank);

            //Select View
            swModel.ClearSelection2(true);
            swView = swDraw.GetCurrentSheet().GetViews()[0];

            //Insert BOM Table
            anchorType = (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopLeft;
            bomType    = (int)swBomType_e.swBomType_TopLevelOnly;

            swModel.ClearSelection2(true);

            configuration = "";

            tableTemplate = "C:\\Program Files\\SW-Complex\\Template.sldbomtbt";

            swBomAnn = swView.InsertBomTable2(false, -0, -0, (int)anchorType, (int)bomType, configuration, tableTemplate);

            swFeatMgr.UpdateFeatureTree();

            swBomFeat = swBomAnn.BomFeature;

            var Names = swBomFeat.GetConfigurations(false, visible);

            visible = true;
            swBomFeat.SetConfigurations(true, visible, Names);
        }
예제 #2
0
        /// <summary>
        /// Returns Lists of Custom_parts and Standard_Parts
        /// </summary>
        /// <param name="swModel"></param>
        /// <param name="swTableAnn"></param>
        /// <param name="ConfigName"></param>
        /// <param name="Standard_Parts"></param>
        /// <param name="Custom_Parts"></param>
        public static void Get_Sorted_Part_Data(ModelDoc2 swModel, BomFeature swBomFeat, List <BOM_Part_Informations> Standard_Parts, List <BOM_Part_Informations> Custom_Parts, string projectpath)
        {
            try
            {
                int nNumRow              = 0;
                int J                    = 0;
                int I                    = 0;
                int numStandard_Part     = 1;
                int numCustom_Part       = 1;
                int quantity             = 0;
                int index_description    = 0;
                int index_article_number = 0;
                int index_supplier       = 0;


                BOM_Part_Informations part_informations;



                string ItemNumber = null;
                string PartNumber = null;

                // Debug.Print("   Table Title        " + swTableAnn.Title);
                Feature  swFeat       = default(Feature);
                object[] vTableArr    = null;
                object   vTable       = null;
                string[] vConfigArray = null;
                object   vConfig      = null;
                string   ConfigName   = null;
                string   partconfig   = null;

                TableAnnotation swTable      = default(TableAnnotation);
                Annotation      swAnnotation = default(Annotation);
                object          visibility   = null;


                swFeat    = swBomFeat.GetFeature();
                vTableArr = (object[])swBomFeat.GetTableAnnotations();

                foreach (TableAnnotation vTable_loopVariable in vTableArr)
                {
                    vTable       = vTable_loopVariable;
                    swTable      = (TableAnnotation)vTable;
                    vConfigArray = (string[])swBomFeat.GetConfigurations(true, ref visibility);

                    foreach (object vConfig_loopVariable in vConfigArray)
                    {
                        vConfig    = vConfig_loopVariable;
                        ConfigName = (string)vConfig;



                        //    MessageBox.Show(ConfigName);


                        // swTable.SaveAsPDF(@"C:\Users\alex\Desktop\test.pdf");



                        nNumRow = swTable.RowCount;

                        BomTableAnnotation swBOMTableAnn = default(BomTableAnnotation);
                        swBOMTableAnn = (BomTableAnnotation)swTable;
                        //swTable.GetColumnTitle
                        for (int h = 0; h < swTable.ColumnCount; h++)
                        {
                            switch (swTable.GetColumnTitle(h))
                            {
                            case "Benennung":
                                index_description = h;
                                break;

                            case "Artikelnummer":
                                index_article_number = h;
                                break;

                            case "Lieferant":
                                index_supplier = h;
                                break;

                            default:
                                break;
                            }
                        }
                        if (index_supplier != 0 || index_supplier != 0 || index_article_number != 0) //Standard BOM Template
                        {
                            for (int n = 0; n <= nNumRow - 1; n++)
                            {
                                // Debug.Print("   Row Number " + J + " Component Count  : " + swBOMTableAnn.GetComponentsCount2(J, ConfigName, out ItemNumber, out PartNumber));
                                //  Debug.Print("       Item Number  : " + ItemNumber);
                                // Debug.Print("       Part Number  : " + PartNumber);
                                // MessageBox.Show("bubu");
                                object[]   vPtArr = null;
                                Component2 swComp = null;
                                object     pt     = null;
                                quantity = swBOMTableAnn.GetComponentsCount2(n, ConfigName, out ItemNumber, out PartNumber);

                                vPtArr = (object[])swBOMTableAnn.GetComponents2(n, ConfigName);

                                if (((vPtArr != null)))
                                {
                                    for (I = 0; I <= vPtArr.GetUpperBound(0); I++)
                                    {
                                        pt     = vPtArr[I];
                                        swComp = (Component2)pt;
                                        if ((swComp != null))
                                        {
                                            part_informations = new BOM_Part_Informations();

                                            part_informations.manufacturer = swTable.get_Text(n, index_supplier);
                                            part_informations.order_number = swTable.get_Text(n, index_article_number);
                                            part_informations.IsAssembly   = false;

                                            part_informations.part_number = PartNumber.TrimStart();
                                            part_informations.quantity    = quantity.ToString();

                                            //Custom part
                                            if (swComp.GetPathName().Contains(projectpath))
                                            {
                                                if (swComp.GetPathName().Contains(".sldasm") || swComp.GetPathName().Contains(".SLDASM"))
                                                {
                                                    // MessageBox.Show(swComp.GetPathName());
                                                    part_informations.IsAssembly = true;
                                                }

                                                part_informations.description = swComp.ReferencedConfiguration;
                                                part_informations.item_number = numCustom_Part.ToString();
                                                numCustom_Part++;

                                                Custom_Parts.Add(part_informations);
                                                break;
                                            }

                                            part_informations.description = swTable.get_Text(n, index_description);
                                            part_informations.item_number = numStandard_Part.ToString();
                                            numStandard_Part++;
                                            Standard_Parts.Add(part_informations);
                                            break;
                                        }
                                        else
                                        {
                                            Debug.Print("  Could not get component.");
                                        }
                                    }
                                }
                            }
                        }
                        else //No Standard BOM Template
                        {
                            for (J = 0; J <= nNumRow - 1; J++)
                            {
                                // Debug.Print("   Row Number " + J + " Component Count  : " + swBOMTableAnn.GetComponentsCount2(J, ConfigName, out ItemNumber, out PartNumber));
                                //  Debug.Print("       Item Number  : " + ItemNumber);
                                // Debug.Print("       Part Number  : " + PartNumber);

                                object[]   vPtArr = null;
                                Component2 swComp = null;
                                object     pt     = null;
                                quantity = swBOMTableAnn.GetComponentsCount2(J, ConfigName, out ItemNumber, out PartNumber);

                                vPtArr = (object[])swBOMTableAnn.GetComponents2(J, ConfigName);

                                if (((vPtArr != null)))
                                {
                                    for (I = 0; I <= vPtArr.GetUpperBound(0); I++)
                                    {
                                        pt     = vPtArr[I];
                                        swComp = (Component2)pt;
                                        if ((swComp != null))
                                        {
                                            part_informations = new BOM_Part_Informations();

                                            part_informations.description = swComp.ReferencedConfiguration;
                                            part_informations.part_number = PartNumber;
                                            part_informations.quantity    = quantity.ToString();
                                            //Custom part
                                            if (swComp.GetPathName().Contains(projectpath))
                                            {
                                                if (swComp.GetPathName().Contains(".sldasm") || swComp.GetPathName().Contains(".SLDASM"))
                                                {
                                                    break;
                                                }
                                                else
                                                {
                                                    part_informations.item_number = numCustom_Part.ToString();
                                                    numCustom_Part++;

                                                    Custom_Parts.Add(part_informations);
                                                    break;
                                                }
                                            }

                                            part_informations.item_number = numStandard_Part.ToString();
                                            numStandard_Part++;
                                            Standard_Parts.Add(part_informations);
                                            break;
                                        }
                                        else
                                        {
                                            Debug.Print("  Could not get component.");
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
                swAnnotation = swTable.GetAnnotation();
                swAnnotation.Select3(false, null);
                swModel.EditDelete();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
예제 #3
0
        public void GetXMLfromBOM()
        {
            swapp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            swmodel = swapp.ActiveDoc;

            swModelDocExt = swmodel.Extension;

            //создаем MemoryStream, в который будем писать XML
            var myMemoryStream = new MemoryStream();

            //создаем XmlTextWriter, указываем объект – myMemoryStream, в который будем писать XML, и кодировку
            try
            {
                var myXml = new System.Xml.XmlTextWriter("C:\\Program Files\\SW-Complex\\SP-Temp.xml", System.Text.Encoding.UTF8);
                swDraw      = (DrawingDoc)swmodel;
                vSheetNames = swDraw.GetSheetNames();
                ok          = swDraw.ActivateSheet(vSheetNames[0]);
                swView      = swDraw.GetFirstView();

                // Получаем параметры модели
                swView  = swView.GetNextView();
                swmodel = swView.ReferencedDocument;

                //swSelMgr = swDraw.SelectionManager;

                myXml.WriteStartDocument();
                myXml.Formatting = System.Xml.Formatting.Indented;

                //длина отступа
                myXml.Indentation = 2;
                vConfName         = swmodel.GetConfigurationNames();


                swapp   = new SldWorks();
                swmodel = swapp.ActiveDoc;

                Feature swFeat = swmodel.FirstFeature();

                while ((swFeat != null))
                {
                    if (swFeat.GetTypeName() == "BomFeat")
                    {
                        swFeat.Select(true);
                        swBomFeature = swFeat.GetSpecificFeature2();
                    }
                    swFeat = swFeat.GetNextFeature();
                }

                //////////////////////////////////////////////////////
                //
                //           GetPropertyBomTableFromDrawDoc
                //
                //////////////////////////////////////////////////////

                object          vConfigurations   = null;
                object          vVisibility       = null;
                bool            bGetVisible       = false;
                long            lNumRow           = 0;
                long            lNumColumn        = 0;
                int             lRow              = 0;
                TableAnnotation swTableAnnotation = default(TableAnnotation);
                ModelDoc2       swDocument        = default(ModelDoc2);
                AssemblyDoc     swAssembly        = default(AssemblyDoc);
                int             lStartRow         = 0;
                string          strItemNumber     = "";
                string          strPartNumber     = "";
                string          strDescription    = "";

                var strDocumentName = swBomFeature.GetReferencedModelName();

                swDocument = swapp.GetOpenDocumentByName(strDocumentName);
                swAssembly = (AssemblyDoc)swDocument;

                //swBOMTableAnnotation = swBomFeature.GetTableAnnotations(0)
                var swBomTableAnnotation = (BomTableAnnotation)swBomFeature.GetTableAnnotations()[0];

                swTableAnnotation = (TableAnnotation)swBomTableAnnotation;

                lNumRow    = swTableAnnotation.RowCount;
                lNumColumn = swTableAnnotation.ColumnCount;

                lStartRow = 1;

                //If (Not (swTableAnnotation.TitleVisible = False)) Then
                if (swTableAnnotation.TitleVisible == false)
                {
                    lStartRow = 2;
                }

                bGetVisible     = false;
                vConfigurations = swBomFeature.GetConfigurations(bGetVisible, vVisibility);

                //swTableAnnotation = swTableAnnotation;

                ///////////////////////////////////////////////////////////////////

                swSheet            = swDraw.GetCurrentSheet();
                strActiveSheetName = swSheet.GetName();
                vSheetNames        = swDraw.GetSheetNames();
                ok      = swDraw.ActivateSheet(vSheetNames[0]);
                swSheet = swDraw.GetCurrentSheet();
                swView  = swDraw.GetFirstView();

                if (swSheet.CustomPropertyView == "По умолчанию" | swSheet.CustomPropertyView == "Default")
                {
                    swView = swView.GetNextView();
                }

                // get custom property

                var valout  = ""; //Обозначение
                var valout1 = ""; //Наименование


                CustomPropertyManager swCustProp = default(CustomPropertyManager);
                var resolvedValOut  = "";
                var resolvedValOut1 = "";
                //string resolvedValOut3 = "";
                //string resolvedValOut4 = "";
                //string resolvedValOut5 = "";
                swCustProp = swmodel.Extension.CustomPropertyManager[""];
                swCustProp.Get2("Обозначение", out valout, out resolvedValOut);
                swCustProp.Get2("Description", out valout1, out resolvedValOut1);

                // переменные для колонок

                int Jj = 0;             // наименование
                int aa = 0;             // раздел
                int oo = 0;             // обозначение
                int tt = 0;             // формат
                int yy = 0;             //
                int uu = 0;             // Код материала
                int ss = 0;             // Примечание

                string sRowStr  = null; // наименовани
                string sRowStr1 = null; // раздел
                string sRowStr2 = null; // обозначение
                string sRowStr3 = null; // формат
                string sRowStr4 = null; // ERP code
                string sRowStr5 = null; // Код материала
                string sRowStr6 = null; // Примечание

                // При выборе электромонтажа
                string Complect = "";

                if (addinform.ChkElectro1.Checked)
                {
                    Complect = "МЭ";
                }
                else if (addinform.ChkElectro2.Checked)
                {
                    Complect = "ТБ";
                }

                ////////////////////////////////////////////////////////////
                //
                //                          XML
                //
                ////////////////////////////////////////////////////////////

                //создаем элементы
                myXml.WriteStartElement("xml");
                //
                myXml.WriteStartElement("Item");

                // имя пути основного чертежа
                myXml.WriteStartElement("PathName");
                //записываем строку
                myXml.WriteString(swmodel.GetPathName());
                myXml.WriteEndElement();

                // Устанавливаем ДОК из формы добавление
                myXml.WriteStartElement("doc");
                //
                myXml.WriteStartElement("Обозначение");
                //записываем строку
                myXml.WriteString(resolvedValOut + "CБ");
                myXml.WriteEndElement();
                //
                myXml.WriteStartElement("Наименование");
                myXml.WriteString("Сборочный чертеж");
                myXml.WriteEndElement();
                //
                myXml.WriteEndElement(); //doc

                //dynamic CheckedRows2 = (from Rows in addinform.DGDoc.Rows.Cast<DataGridViewRow>()where Convert.ToBoolean(Rows.Cells(0).Value) == true).ToList;

                dynamic CheckedRows2 = (from Rows in addinform.DGDoc.Rows.Cast <DataGridViewRow>() where Convert.ToBoolean(Rows.Cells[0].Value.ToString()) select Rows).ToList();


                System.Text.StringBuilder sb = new System.Text.StringBuilder();

                foreach (DataGridViewRow row in CheckedRows2)
                {
                    sb.AppendLine(row.Cells[1].Value.ToString());
                    sb.ToString();

                    //Оставляем первые две буквы для обозначения разделитель

                    var literal   = row.Cells[1].Value.ToString();
                    var substring = literal.Substring(0, 2);

                    var literal2   = row.Cells[1].Value.ToString();
                    var substring2 = literal2.Substring(5);

                    myXml.WriteStartElement("doc");
                    ///
                    myXml.WriteStartElement("Обозначение");
                    //записываем строку
                    myXml.WriteString(resolvedValOut + substring);
                    myXml.WriteEndElement();
                    ///
                    myXml.WriteStartElement("Наименование");
                    myXml.WriteString(substring2);
                    myXml.WriteEndElement();
                    ///
                    myXml.WriteEndElement();
                    //doc
                }


                //<------------- Elec
                if (addinform.ChkElectro.Checked == true & addinform.ChkElectro1.Checked == false & addinform.ChkElectro2.Checked == false)
                {
                    myXml.WriteStartElement("Elec");
                    //Elec

                    myXml.WriteString("Устанавливают при электромонтаже");
                    myXml.WriteEndElement();
                    //Elec
                }

                //<------------- ChkElectro1
                if (addinform.ChkElectro.Checked == true & addinform.ChkElectro1.Checked == true)
                {
                    myXml.WriteStartElement("Elec");
                    //Elec
                    myXml.WriteString("Устанавливают по " + resolvedValOut + Complect);
                    myXml.WriteEndElement();
                    //Elec
                }

                //<------------- ChkElectro2
                if (addinform.ChkElectro.Checked == true & addinform.ChkElectro2.Checked == true)
                {
                    myXml.WriteStartElement("Elec");
                    //Elec
                    myXml.WriteString("Устанавливают по " + resolvedValOut + Complect);
                    myXml.WriteEndElement();
                    //Elec
                }

                //
                myXml.WriteStartElement("Обозначение");
                //записываем строку
                myXml.WriteString(resolvedValOut);
                myXml.WriteEndElement();
                ///
                myXml.WriteStartElement("Наименование");
                myXml.WriteString(resolvedValOut1);
                myXml.WriteEndElement();

                //\reference
                myXml.WriteStartElement("references");

                // ВЫГРУЖАЕМ ВЫБРАННЫЕ КОНФИГУРАЦИИ

                dynamic CheckedRows           = (from Rows in DataGridConfig.Rows.Cast <DataGridViewRow>() where Convert.ToBoolean(Rows.Cells[0].Value.ToString()) select Rows).ToList();
                System.Text.StringBuilder sb2 = new System.Text.StringBuilder();

                foreach (DataGridViewRow row in CheckedRows)
                {
                    sb2.AppendLine(row.Cells[1].Value.ToString());

                    swmodel = swView.ReferencedDocument;
                    var configuration = swView.ReferencedConfiguration;

                    var           sConfigName = swView.ReferencedConfiguration;
                    Configuration swConfig    = swmodel.GetConfigurationByName(sConfigName);

                    for (var i = 0; i <= vConfName.GetUpperBound(0); i++)
                    {
                        const string ucase = "";

                        if (vConfName[i] == row.Cells[1].Value.ToString())
                        {
                            configuration = vConfName[i];
                        }
                    }

                    swView.ReferencedConfiguration = sConfigName;

                    myXml.WriteStartElement("config");
                    myXml.WriteAttributeString("value", row.Cells[1].Value.ToString());


                    /////////////////////////////////////////////////////////////
                    //
                    //                           PART
                    //
                    /////////////////////////////////////////////////////////////

                    for (lRow = lStartRow; lRow <= (lNumRow - 1); lRow++)
                    {
                        if (swBomTableAnnotation.GetComponentsCount2((int)lRow, row.Cells[1].Value.ToString(), out strItemNumber, out strPartNumber) > 0)
                        {
                            myXml.WriteStartElement("part");
                            //PathNameComponent
                            string strModelPathName = null;
                            var    vModelPathNames  = swBomTableAnnotation.GetModelPathNames((int)lRow, out strItemNumber, out strPartNumber);
                            if (((vModelPathNames != null)))
                            {
                                myXml.WriteStartElement("PathNameComponent");
                                foreach (var vModelPathName_loopVariable in vModelPathNames)
                                {
                                    var vModelPathName = vModelPathName_loopVariable;
                                    strModelPathName = vModelPathName;
                                    myXml.WriteString(strModelPathName);
                                }
                                myXml.WriteEndElement();
                            }
                            //'\ Row
                            myXml.WriteStartElement("Row");
                            myXml.WriteString(Convert.ToString(lRow - lStartRow + 1));
                            myXml.WriteEndElement();
                            vModelPathNames = swBomTableAnnotation.GetModelPathNames((int)lRow, out strItemNumber, out strPartNumber);
                            //\ ItemNum
                            myXml.WriteStartElement("ItemNum");
                            myXml.WriteString(strItemNumber);
                            myXml.WriteEndElement();
                            //\ раздел
                            aa = 3;
                            /// раздел
                            sRowStr1 = "";
                            sRowStr1 = sRowStr1 + swTableAnnotation.Text[lRow, aa];
                            myXml.WriteStartElement("Раздел");
                            myXml.WriteString(sRowStr1);
                            myXml.WriteEndElement();
                            //\ обозначение
                            oo = 1;
                            /// обозначение
                            sRowStr2 = "";
                            sRowStr2 = sRowStr2 + swTableAnnotation.Text[lRow, oo];
                            myXml.WriteStartElement("Обозначение");
                            myXml.WriteString(sRowStr2);
                            myXml.WriteEndElement();
                            //\ наименование
                            Jj = 2;
                            /// наименование
                            sRowStr = "";
                            sRowStr = sRowStr + swTableAnnotation.Text[lRow, Jj];
                            myXml.WriteStartElement("Наименование");
                            myXml.WriteString(sRowStr);
                            myXml.WriteEndElement();
                            //\
                            tt = 4;
                            /// формат
                            sRowStr3 = "";
                            sRowStr3 = sRowStr3 + swTableAnnotation.Text[lRow, tt];
                            myXml.WriteStartElement("Формат");
                            myXml.WriteString(sRowStr3);
                            myXml.WriteEndElement();
                            //\
                            yy = 5;
                            /// ERP code
                            sRowStr4 = "";
                            sRowStr4 = sRowStr4 + swTableAnnotation.Text[lRow, yy];
                            myXml.WriteStartElement("ERP_code");
                            myXml.WriteString(sRowStr4);
                            myXml.WriteEndElement();
                            //\
                            uu = 6;
                            /// Код материала
                            sRowStr5 = "";
                            sRowStr5 = sRowStr5 + swTableAnnotation.Text[lRow, uu];
                            myXml.WriteStartElement("Код_материала");
                            myXml.WriteString(sRowStr5);
                            myXml.WriteEndElement();
                            //\
                            ss = 7;
                            /// наименование
                            sRowStr6 = "";
                            sRowStr6 = sRowStr6 + swTableAnnotation.Text[lRow, ss];
                            myXml.WriteStartElement("Примечание");
                            myXml.WriteString(sRowStr6);
                            myXml.WriteEndElement();
                            //\

                            myXml.WriteStartElement("Количество");
                            //myXml.WriteString(swTableAnnotation.GetComponentsCount2(lRow, strConfiguration, strItemNumber, strPartNumber))
                            myXml.WriteString(Convert.ToString(swBomTableAnnotation.GetComponentsCount2(lRow, row.Cells[1].Value.ToString(), out strItemNumber, out strPartNumber)));
                            myXml.WriteEndElement();
                            myXml.WriteEndElement();
                            //config
                        }
                    }


                    myXml.WriteEndElement(); //part
                }


                myXml.WriteEndElement(); //references
                //<~~~~~~~~~~~~~~~~~~~~~~~~~~~ Get the Total Number of Rows


                Annotation      swAnn   = default(Annotation);
                TableAnnotation swTable = default(TableAnnotation);
                long            nNumRow = 0;

                swmodel = swapp.ActiveDoc;

                swView  = swDraw.GetFirstView();
                swTable = swView.GetFirstTableAnnotation();
                swAnn   = swTable.GetAnnotation();

                nNumRow = swTable.RowCount;
                myXml.WriteStartElement("TotalRows");
                myXml.WriteString(Convert.ToString(nNumRow));
                myXml.WriteEndElement();
                //end TotalRows

                myXml.WriteEndElement();
                //Item
                myXml.WriteEndElement();
                //элемент XML

                //End If
                //заносим данные в myMemoryStream
                myXml.Flush();
                myXml.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
        }
예제 #4
0
파일: Drawings.cs 프로젝트: mdcnbu/TDG
        /// <summary>
        /// 出工程图
        /// </summary>
        /// <param name="dicValues"></param>
        /// <param name="prtTemp"></param>
        /// <param name="compTemp"></param>
        /// <param name="bomPaths"></param>
        /// <param name="savePaths">保存路径</param>
        /// <param name="newPath">新路径</param>
        private void Drawing(List <string> dicValues, string prtTemp, string compTemp, string bomPaths, string savePaths, string newPath)
        {
            string          viewType   = string.Empty;
            bool            isometric  = false;
            bool            bom        = false;
            string          dimesion   = string.Empty;
            double          spaceX     = 0.06;                  //x方向留白区域
            double          scale      = 1;                     //定义比例初始值
            List <double[]> viewBox    = new List <double[]>(); //集合存放视图box
            List <double[]> viewOrigin = new List <double[]>(); //集合存放视图原点值

            double[] outLine = new double[4];                   //视图box值
            double[] postion = new double[2];                   //视图原点值
            _swApp = (SldWorks)ConnectSW.iSwApp;                //连接sw
            if (_swApp == null)
            {
                return;
            }
            foreach (string item in dicValues)
            {
                int    errors   = 0;
                int    warnings = 0;
                double view1X   = 0;
                double view1Y   = 0;
                string filePath = item;                                             //文件路径
                string fileEx   = filePath.Substring(filePath.LastIndexOf("."), 7); //获得后缀名
                string filename = filePath.Substring(filePath.LastIndexOf("\\") + 1, filePath.LastIndexOf(".") - filePath.LastIndexOf("\\") - 1);
                if (fileEx == ".SLDPRT")
                {
                    _swModelDoc = (ModelDoc2)_swApp.OpenDoc6(filePath, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
                    __swDrawDoc = (DrawingDoc)_swApp.NewDrawing2((int)swDwgTemplates_e.swDwgTemplateCustom, prtTemp, (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 0, 0);
                }
                if (fileEx == ".SLDASM")
                {
                    _swModelDoc = (ModelDoc2)_swApp.OpenDoc6(filePath, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
                    __swDrawDoc = (DrawingDoc)_swApp.NewDrawing2((int)swDwgTemplates_e.swDwgTemplateCustom, compTemp, (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 0, 0);
                }
                _swModelEx = (ModelDocExtension)_swModelDoc.Extension;
                if (newPath != null)
                {
                    savePaths = newPath.Substring(0, newPath.LastIndexOf("\\"));
                }
                //新建工程图
                _swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swAutomaticScaling3ViewDrawings, true); //自动缩放新工程图比例
                if (standarView == false && isometric)                                                               //如果只生成等轴测视图
                {
                    CreatIsometric(__swDrawDoc, filePath);
                    _currentSheet = (Sheet)__swDrawDoc.GetCurrentSheet();
                    __swDrawDoc.ActivateSheet(_currentSheet.GetName());
                    _swView = __swDrawDoc.GetFirstView();
                    _swView = _swView.GetNextView();
                    ChangeViewShow(tag, _swView);
                    _swApp.CloseDoc(_swModelDoc.GetTitle());//
                    ModelDoc2 tempDoc = (ModelDoc2)__swDrawDoc;
                    bool      ss0     = false;
                    if (newPath != null && IfDwg)
                    {
                        ss0 = tempDoc.Extension.SaveAs(newPath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                    }
                    else if (newPath != null && IfDwg == false)
                    {
                        ss0 = tempDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()).Substring(0, (_swModelDoc.GetTitle()).LastIndexOf(".")) + ".DWG", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                    }
                    else if (newPath == null && IfDwg)
                    {
                        ss0 = tempDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()).Substring(0, (_swModelDoc.GetTitle()).LastIndexOf(".")) + ".DWG", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                    }
                    else
                    {
                        ss0 = tempDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()).Substring(0, (_swModelDoc.GetTitle()).LastIndexOf(".")) + ".slddrw", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                    }

                    bool isHidden = tempDoc.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swViewDisplayHideAllTypes, true); //隐藏所有类型
                    _swApp.CloseDoc(tempDoc.GetTitle());
                    _numSucess += 1;                                                                                                //转换成功的数量
                    sucessFile.Add(filePath);
                    return;
                }
                bool isCreate = false;
                #region 第三视角投影
                if (thirProject)
                {
                    isCreate = __swDrawDoc.Create3rdAngleViews2(filePath);//创建第三视角投影视图(视图位置有差别)
                    //调整视图位置
                    _swView = __swDrawDoc.GetFirstView();
                    while (_swView != null)
                    {
                        double[] vBox   = new double[] { };
                        double[] vPoint = new double[] { };
                        vBox   = (double[])_swView.GetOutline();
                        vPoint = (double[])_swView.Position;
                        viewBox.Add(vBox);
                        viewOrigin.Add(vPoint);
                        _swView = _swView.GetNextView();
                    }
                    //调整视图1、2位置
                    if (viewBox[0][3] > viewBox[0][2])//纵向
                    {
                        double[] posView1 = new double[] { viewBox[0][2] / 3.0, viewOrigin[1][1] };
                        _swView          = __swDrawDoc.GetFirstView();
                        _swView          = _swView.GetNextView();
                        _swView.Position = posView1;
                        double[] posView2 = new double[] { viewOrigin[2][0], viewOrigin[2][1] - (viewBox[2][1] - viewBox[1][3]) / 1.9 };//调整视图2位置
                        _swView          = _swView.GetNextView();
                        _swView.Position = posView2;
                    }
                    else
                    {
                        double[] posView1 = new double[] { viewBox[0][2] / 4.0, viewOrigin[1][1] };
                        _swView          = __swDrawDoc.GetFirstView();
                        _swView          = _swView.GetNextView();
                        _swView.Position = posView1;
                        double[] posView2 = new double[] { viewOrigin[2][0], viewOrigin[2][1] - (viewBox[2][1] - viewBox[1][3]) / 2.0 };//调整视图2位置
                        _swView          = _swView.GetNextView();
                        _swView.Position = posView2;
                    }
                    viewOrigin.Clear();
                    viewBox.Clear();
                    _swView = __swDrawDoc.GetFirstView();
                    while (_swView != null)
                    {
                        double[] vBox   = new double[] { };
                        double[] vPoint = new double[] { };
                        vBox   = (double[])_swView.GetOutline();
                        vPoint = (double[])_swView.Position;
                        viewBox.Add(vBox);
                        viewOrigin.Add(vPoint);
                        _swView = _swView.GetNextView();
                    }
                    if (isometric)//等轴测
                    {
                        _swView = (IView)__swDrawDoc.CreateDrawViewFromModelView3(filePath, "*等轴测", viewOrigin[3][0], viewOrigin[2][1], 0);
                        _swView = __swDrawDoc.GetFirstView();
                        double[] sca = new double[2];
                        sca                = _swView.ScaleRatio;//获取比例
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView.ScaleRatio = sca;
                        double[] rePos = new double[] { viewOrigin[3][0] + 0.015, viewOrigin[2][1] };
                        _swView.Position = rePos;
                        ChangeViewShow(tag, _swView);                     //视图样式
                        AddDimension(dimesion, __swDrawDoc, _swModelDoc); //尺寸标注
                    }
                }
                #endregion
                #region 第一视角投影
                else
                {
                    isCreate = __swDrawDoc.Create1stAngleViews(filePath);//创建第一视角投影视图
                    //获取视图boundingbox
                    _swView = __swDrawDoc.GetFirstView();
                    while ((_swView != null))
                    {
                        outLine = (double[])_swView.GetOutline(); //(x,y坐标最值)
                        postion = (double[])_swView.Position;     //视图位置值
                        viewBox.Add(outLine);
                        viewOrigin.Add(postion);
                        _swView = _swView.GetNextView();
                    }

                    double newScale = CalcuScale(viewBox, __swDrawDoc, scale, spaceX, 3);
                    //调整视图位置(position)
                    if (viewBox[0][3] > viewBox[0][2])
                    {
                        view1X = viewBox[0][2] / 2.8;                  //视图1的X坐标放在图纸坐标的三分之一处
                        view1Y = viewBox[0][3] - viewBox[0][3] / 4.85; //视图1的Y坐标放在图纸坐标的五分之一处
                    }
                    else
                    {
                        view1X = viewBox[0][2] / 3.5;                 //视图1的X坐标放在图纸坐标的三分之一处
                        view1Y = viewBox[0][3] - viewBox[0][3] / 4.0; //视图1的Y坐标放在图纸坐标的四分之一处
                    }
                    double[] view1Pos = new double[] { view1X, view1Y };
                    _swView          = __swDrawDoc.GetFirstView(); //获取图纸
                    _swView          = _swView.GetNextView();      //获取第一个视图
                    _swView.Position = view1Pos;
                    bool isRebuild = _swModelDoc.EditRebuild3();
                    //viewBox.Clear();
                    List <double[]> tempBox = new List <double[]>();
                    viewOrigin.Clear();
                    while ((_swView != null))
                    {
                        ChangeViewShow(tag, _swView);                     //改变视图显示样式
                        AddDimension(dimesion, __swDrawDoc, _swModelDoc); //添加尺寸
                        outLine = (double[])_swView.GetOutline();         //(x,y坐标最值)
                        postion = (double[])_swView.Position;             //视图位置值
                        tempBox.Add(outLine);
                        viewOrigin.Add(postion);
                        _swView = _swView.GetNextView();
                    }
                    if (isometric)  //是否创建等轴测视图(非钣金)
                    {
                        double[] scalArry = new double[2];
                        _swView = (IView)__swDrawDoc.CreateDrawViewFromModelView3(filePath, "*等轴测", viewOrigin[2][0], viewOrigin[1][1], 0);
                        _swView = __swDrawDoc.GetFirstView(); //获取图纸
                        _swView = _swView.GetNextView();      //获取第一个视图
                        double sca = _swView.get_IScaleRatio();
                        if (sca == 1)                         //缩小比例
                        {
                            scalArry[0] = 1;
                            scalArry[1] = newScale;
                        }
                        else
                        {
                            scalArry[0] = sca;
                            scalArry[1] = 1;
                        }
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView.ScaleRatio = scalArry;//调整轴测图比例
                        ChangeViewShow(tag, _swView);
                        _swModelDoc.EditRebuild3();
                    }
                    ////关掉文件(不保存)
                    //_swApp.CloseDoc(_swModelDoc.GetTitle());
                    if (fileEx == ".SLDASM" && bom)        //是否创建明细表
                    {
                        //viewBox.Clear();
                        //viewOrigin.Clear();
                        double[] outArry  = new double[4];
                        double[] posArry  = new double[2];
                        double[] posArry1 = null;
                        double[] posArry2 = null;
                        double[] posArry3 = null;
                        _currentSheet = (Sheet)__swDrawDoc.GetCurrentSheet();
                        __swDrawDoc.ActivateSheet(_currentSheet.GetName());
                        _swView        = __swDrawDoc.GetFirstView(); //获取图纸
                        _swView        = _swView.GetNextView();      //获取第一个视图
                        swBomTableAnno = (BomTableAnnotation)_swView.InsertBomTable4(true, 0.4, 0.1, (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_BottomRight, (int)swBomType_e.swBomType_TopLevelOnly, "", bomPaths, false, 0, false);
                        TableAnnotation tableAnnotation = (TableAnnotation)swBomTableAnno;
                        tableAnnotation.GetAnnotation();
                        BomFeature bomFeature     = swBomTableAnno.BomFeature;
                        bool[]     array          = new bool[bomFeature.GetConfigurationCount(false)];
                        object     Visible        = array;
                        object     configurations = bomFeature.GetConfigurations(false, ref Visible);
                        array[0] = true;
                        bomFeature.SetConfigurations(true, array, configurations);
                        FeatureManager featureManager = _swModelDoc.FeatureManager;
                        featureManager.UpdateFeatureTree();
                        double num = 0.007;
                        tableAnnotation.SetRowHeight(-2, num, 0);
                        double totleHeight = num * tableAnnotation.RowCount; //计算总的tableBom高度
                        double heightSum   = totleHeight + 0.070;            //加上标题栏总高度
                        int    columCount  = tableAnnotation.ColumnCount;    //获取总的列数
                        double columWidth  = 0;
                        for (int i = 0; i < columCount; i++)
                        {
                            double wid = tableAnnotation.GetColumnWidth(i);
                            columWidth += wid;
                        }
                        _swView = _swView.GetNextView();
                        _swView = _swView.GetNextView();
                        outArry = (double[])_swView.GetOutline();
                        if (outArry[1] < heightSum)//有可能被遮挡
                        {
                            //__swView = _swDrawDoc.GetFirstView();
                            //double[] tempArry = new double[] { };
                            //tempArry=(double[])__swView.GetOutline();
                            //viewBox.Insert(0, tempArry);
                            scale = ((viewBox[1][2] - viewBox[1][0]) + (viewBox[3][2] - viewBox[3][0])) / (viewBox[0][2] - columWidth - 0.025);//计算X方向的比例
                            if (scale > 11)
                            {
                                double scaleCeil = System.Math.Ceiling(scale);
                                if (scaleCeil > 11 && scaleCeil < 16)
                                {
                                    scale = 20;
                                }
                                if (scaleCeil > 15 && scaleCeil < 21)
                                {
                                    scale = 25;
                                }
                                if (scaleCeil > 20 && scaleCeil < 26)
                                {
                                    scale = 30;
                                }
                                if (scaleCeil > 25 && scaleCeil < 34)
                                {
                                    scale = 40;
                                }
                                if (scaleCeil > 33 && scaleCeil < 45)
                                {
                                    scale = 50;
                                }
                                if (scaleCeil > 44 && scaleCeil < 55)
                                {
                                    scale = 60;
                                }
                            }
                            else if (scale > 5.8 && scale < 10.5)
                            {
                                double scaleCeil = System.Math.Ceiling(scale);
                                //scale = scaleCeil + 4.0;          //比例为10、11、12、13、14、15
                                if (scaleCeil > 5 && scaleCeil < 8)
                                {
                                    scale = 10;
                                }
                                if (scaleCeil > 7 && scaleCeil < 12)
                                {
                                    scale = 15;
                                }
                            }
                            _currentSheet = (Sheet)__swDrawDoc.GetCurrentSheet();
                            __swDrawDoc.ActivateSheet(_currentSheet.GetName());
                            bool isScale = _currentSheet.SetScale(1, scale, false, false); //设置视图和图纸比例
                            _swView = __swDrawDoc.GetFirstView();
                            _swView = _swView.GetNextView();                               //获取视图1
                            double[] pos1 = new double[2];
                            pos1             = _swView.Position;
                            posArry1         = new double[] { pos1[0] - columWidth / 3.45, pos1[1] };
                            _swView.Position = posArry1;              //重置视图1的位置
                            _swView          = _swView.GetNextView(); //获取视图2
                            double[] pos2 = new double[2];
                            pos2             = _swView.Position;
                            posArry2         = new double[] { pos2[0] - columWidth / 3.45, pos2[1] + 0.0015 };
                            _swView.Position = posArry2;              //设置视图2位置
                            _swView          = _swView.GetNextView(); //获取视图三
                            posArry          = (double[])_swView.Position;
                            posArry3         = new double[] { posArry[0] - columWidth / 3.5, posArry[1] };
                            _swView.Position = posArry3;//视图3坐标
                        }
                    }
                }//第一视角投影
                #endregion
                if (isCreate)
                {
                    _numSucess += 1;//转换成功的数量
                    sucessFile.Add(filePath);
                }
                ModelDoc2 tempModelDoc = (ModelDoc2)__swDrawDoc;                                                                    //获取到swDraw的父级(ModelDoc)
                _swApp.CloseDoc(_swModelDoc.GetTitle());
                bool isHiden = tempModelDoc.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swViewDisplayHideAllTypes, true); //隐藏所有类型

                _swModelDoc.ForceRebuild3(false);
                string saveName = (_swModelDoc.GetTitle()).Substring(0, (_swModelDoc.GetTitle()).LastIndexOf("."));
                bool   ss;
                if (newPath != null && IfDwg)
                {
                    ss = tempModelDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()) + ".DWG", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                }
                else if (newPath != null && IfDwg == false)
                {
                    ss = tempModelDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()) + ".slddrw", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                }
                else if (newPath == null && IfDwg)
                {
                    ss = tempModelDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()) + ".DWG", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                }
                else
                {
                    ss = tempModelDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()) + ".slddrw", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                }
                _swApp.CloseDoc(tempModelDoc.GetTitle());//关闭转换完成的文件
            }
        }