明经CAD社区

 找回密码
 注册

QQ登录

只需一步,快速开始

搜索
查看: 2096|回复: 4

[表格] 关于表格的代码,共享给大家

  [复制链接]
发表于 2020-5-17 16:18 | 显示全部楼层 |阅读模式
论坛里面表格相关的代码太少了,我共享下

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Colors;
namespace TableCreation
{
    public class Commands
    {
        [CommandMethod("CRT1")]
        static public void CreateTable1()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            ObjectId appDictId = ObjectId.Null;
            //DBDictionary appDict = new DBDictionary();
            TableStyle myTableStyle = new TableStyle();
            PromptPointResult pr = ed.GetPoint("\nEnter table insertion point: ");
            if (pr.Status == PromptStatus.OK)
            {
                Transaction tr = doc.TransactionManager.StartTransaction();
                using (tr)
                {
                    BlockTable bt = (BlockTable)tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead);
                    Table tb = new Table();
                    DBDictionary nod = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead);//获取数据库object,并转换为DBDictionary
                    if (nod.Contains("ACAD_TABLESTYLE"))//包含这个字典
                    {
                        DBDictionary compDict = (DBDictionary)tr.GetObject(nod.GetAt("ACAD_TABLESTYLE"), OpenMode.ForRead);
                        if (!compDict.Contains("Standard"))
                        {
                            compDict.UpgradeOpen();
                            appDictId = compDict.SetAt("Standard", myTableStyle);
                            tr.AddNewlyCreatedDBObject(myTableStyle, true);
                        }
                        else
                        {
                            appDictId = compDict.GetAt("Standard");
                            myTableStyle = (TableStyle)tr.GetObject(compDict.GetAt("Standard"), OpenMode.ForRead);
                           
                        }
                        myTableStyle.UpgradeOpen();//这个是必须的,否则会有问题的
                        myTableStyle.FlowDirection = FlowDirection.NotSet;//LeftToRight从下往上,NotSet从上往下,如果下面表格再设置就会不按照样式来
                        myTableStyle.IsTitleSuppressed = false;// tb.TableStyle = myTableStyle.ObjectIdb必须要有这个语句才起作用
                        myTableStyle.IsHeaderSuppressed = false;
                        
                        //myTableStyle.DowngradeOpen();
                    }
                    tb.TableStyle = myTableStyle.ObjectId;//这个语句很关键,如果没有下面tb的很多设置不起作用
                    tb.IsTitleSuppressed = false;
                    tb.IsHeaderSuppressed = false;
                    tb.FlowDirection = FlowDirection.LeftToRight;//如果没有tb.TableStyle = myTableStyle.ObjectId,则这个无论怎么设置似乎都不起作用
                    //FlowDirection myFlowDirection = FlowDirection.BottomToTop;//BottomToTop,不存在的,似乎桌子公司错了
                    
                    tb.NumRows = 7;
                    // Added an additional column for the block image
                    // and one for the "is dynamic" flag
                    tb.NumColumns = 9;
                    tb.SetRowHeight(3);
                    tb.SetColumnWidth(15);
                    tb.Rows[0].Height = 10;
                    tb.Rows[1].Height = 20;
                    tb.Rows[2].Height = 30;
                    tb.Columns[0].Width = 30;
                    tb.Columns[1].Width = 40;
                    tb.Columns[2].Width = 60;
                    tb.Position = pr.Value;
                    // Create a 2-dimensional array
                    // of our table contents
                    string[,] str = new string[5, 3];
                    str[0, 0] = "Part No.";
                    str[0, 1] = "Name";
                    str[0, 2] = "Material ";
                    str[1, 0] = "1876-1";
                    str[1, 1] = "Flange";
                    str[1, 2] = "Perspex";
                    str[2, 0] = "0985-4";
                    str[2, 1] = "Bolt";
                    str[2, 2] = "Steel";
                    str[3, 0] = "3476-K";
                    str[3, 1] = "Tile";
                    str[3, 2] = "Ceramic";
                    str[4, 0] = "8734-3";
                    str[4, 1] = "Kean";
                    str[4, 2] = "Mostly water";
                    // Use a nested loop to add and format each cell
                    for (int i = 0; i < 5; i++)
                    {
                        for (int j = 0; j < 3; j++)
                        {
                            tb.Cells[i, j].TextHeight = 1;//tb.SetTextHeight(i, j, 1);
                            tb.Cells[i, i].TextString = str[i, j];//tb.SetTextString(i, j, str[i, j]);
                            tb.Cells[i, i].Alignment = CellAlignment.MiddleCenter; //tb.SetAlignment(i, j, CellAlignment.MiddleCenter);
                        }
                        // Adding title information for additional columns
                        if (i == 0)
                        {
                            tb.SetTextHeight(i, 3, 1);
                            tb.Cells[i, 3].TextString = "Block Preview"; //tb.SetTextString(i, 3, "Block Preview");
                            tb.SetAlignment(i, 3, CellAlignment.MiddleCenter);
                            tb.SetTextHeight(i, 4, 1);
                            tb.Cells[i, 4].TextString = "Is Dynamic?"; //tb.SetTextString(i, 4, "Is Dynamic?");
                            tb.SetAlignment(i, 4, CellAlignment.MiddleCenter);
                        }
                        // If a block definition exists for a block of our
                        // "name" field, then let's set it in the 4th column
                        if (bt.Has(str[i, 1]))
                        {
                            ObjectId objId = bt[str[i, 1]];
                            Cell c=tb.Cells[i,3];
                            c.Contents.Add();
                            // Set the horizontal margins
                            c.Borders.Left.Margin =0.5;// horMarg;
                            c.Borders.Right.Margin = 0.5;//horMarg;
                            // Set the vertical margins
                            c.Borders.Top.Margin = 0.8;//verMarg;
                            c.Borders.Bottom.Margin = 0.8;//verMarg;
                            //CellBorder myCellBorder = c.Borders.Bottom;
                            //myCellBorder.Color = Color.FromColorIndex(ColorMethod.ByAci, 1);
                            c.Borders.Bottom.Color = Color.FromColorIndex(ColorMethod.ByAci, 1);//1代表红色
                            c.Contents[0].BlockTableRecordId = objId;
                           
                            //tb.SetBlockTableRecordId(i, 3, objId, true);
                           
                            // And then we use a field to check on whether
                            // it's a dynamic block or not
                            string strObjId = objId.ToString();
                            strObjId = strObjId.Trim(new char[] { '(', ')' });
                            tb.SetTextHeight(i, 4, 1);
                            tb.SetTextString(i, 4, "%<\\AcObjProp Object(%<\\_ObjId " + strObjId + ">%).IsDynamicBlock \\f \"%bl2\">%");
                            tb.SetAlignment(i, 4, CellAlignment.MiddleCenter);
                        }
                    }
                    //非常重要,根据当前样式更新表格,不加此句,会导致AutoCAD崩溃
                    tb.GenerateLayout();
                    //tb.FlowDirection = Autodesk.AutoCAD.DatabaseServices.FlowDirection.TopToBottom;
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    btr.AppendEntity(tb);
                    tr.AddNewlyCreatedDBObject(tb, true);
                    tr.Commit();
                }
            }
        }

        [CommandMethod("CRT")]
        static public void CreateTable()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            ObjectId appDictId = ObjectId.Null;
            //DBDictionary appDict = new DBDictionary();
            TableStyle myTableStyle = new TableStyle();
            PromptPointResult pr = ed.GetPoint("\nEnter table insertion point: ");
            if (pr.Status == PromptStatus.OK)
            {
                Transaction tr = doc.TransactionManager.StartTransaction();
                using (tr)
                {
                    BlockTable bt = (BlockTable)tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead);
                    Table tb = new Table();
                    DBDictionary nod = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead);//获取数据库object,并转换为DBDictionary
                    if (nod.Contains("ACAD_TABLESTYLE"))//包含这个字典
                    {
                        DBDictionary compDict = (DBDictionary)tr.GetObject(nod.GetAt("ACAD_TABLESTYLE"), OpenMode.ForRead);
                        if (!compDict.Contains("Standard1"))
                        {
                            compDict.UpgradeOpen();
                            appDictId = compDict.SetAt("Standard1", myTableStyle);
                            tr.AddNewlyCreatedDBObject(myTableStyle, true);
                        }
                        else
                        {
                            appDictId = compDict.GetAt("Standard1");
                            myTableStyle = (TableStyle)tr.GetObject(compDict.GetAt("Standard1"), OpenMode.ForRead);
                        }
                        myTableStyle.UpgradeOpen();//这个是必须的,否则会有问题的
                        myTableStyle.FlowDirection = FlowDirection.NotSet;//LeftToRight从下往上,NotSet从上往下,如果下面表格再设置就会不按照样式来
                        myTableStyle.IsTitleSuppressed = false;// tb.TableStyle = myTableStyle.ObjectIdb必须要有这个语句才起作用
                        myTableStyle.IsHeaderSuppressed = false;
                        //myTableStyle.DowngradeOpen();
                    }
                    tb.TableStyle = myTableStyle.ObjectId;//这个语句很关键,如果没有下面tb的很多设置不起作用
                    tb.IsTitleSuppressed = true;
                    tb.IsHeaderSuppressed = true;
                    tb.FlowDirection = FlowDirection.LeftToRight;//如果没有tb.TableStyle = myTableStyle.ObjectId,则这个无论怎么设置似乎都不起作用
                    //FlowDirection myFlowDirection = FlowDirection.BottomToTop;//BottomToTop,不存在的,似乎桌子公司错了
                    tb.SetSize(10, 5);//设置行列数目   //旧的方式 tb.NumRows = 7 //tb.NumColumns = 7;
                    tb.SetRowHeight(5);//设置行高
                    tb.SetColumnWidth(15);// 设置列宽
                    //tb.Columns[0].Width = 20; // 设置第一列宽度为20
                    tb.Position = pr.Value;
                    // Create a 2-dimensional array
                    // of our table contents
                    string[,] str = new string[5, 4];
                    str[0, 0] = "Part No.";
                    str[0, 1] = "Name";
                    str[0, 2] = "Material ";
                    str[1, 0] = "1876-1";
                    str[1, 1] = "Flange";
                    str[1, 2] = "Perspex";
                    str[2, 0] = "0985-4";
                    str[2, 1] = "Bolt";
                    str[2, 2] = "Steel";
                    str[3, 0] = "3476-K";
                    str[3, 1] = "Tile";
                    str[3, 2] = "Ceramic";
                    str[4, 0] = "8734-3";
                    str[4, 1] = "Kean";
                    str[4, 2] = "Mostly water";
                    // Use a nested loop to add and format each cell
                    for (int i = 0; i < 5; i++)
                    {
                        for (int j = 0; j < 3; j++)
                        {
                            tb.SetTextHeight(i, j, 1);
                            tb.Cells[i, j].TextString = str[i, j];  //旧的方式,tb.SetTextString(i, j, str[i, j]);
                            tb.SetAlignment(i, j, CellAlignment.MiddleCenter);
                            tb.Cells.Borders.Bottom.Color=Color.FromColorIndex(ColorMethod.ByAci, 1);//1代表红色
                        }
                        // Adding title information for additional columns
                        if (i == 0)
                        {
                            tb.SetTextHeight(i, 3, 1);
                            tb.Cells[i, 3].TextString = "Block Preview";
                            tb.SetAlignment(i, 3, CellAlignment.MiddleCenter);
                            tb.SetTextHeight(i, 4, 1);
                            tb.Cells[i, 4].TextString = "Is Dynamic?";
                            tb.SetAlignment(i, 4, CellAlignment.MiddleCenter);
                        }
                        // If a block definition exists for a block of our
                        // "name" field, then let's set it in the 4th column
                        if (bt.Has(str[i, 1]))
                        {
                            ObjectId objId = bt[str[i, 1]];
                            tb.SetBlockTableRecordId(i, 3, objId, true);
                            //tb.Cells[i, 3].Contents[0].BlockTableRecordId = objId;
                            // And then we use a field to check on whether
                            // it's a dynamic block or not
                            string strObjId = objId.ToString();
                            strObjId = strObjId.Trim(new char[] { '(', ')' });
                            tb.SetTextHeight(i, 4, 1);
                            tb.Cells[i, 4].TextString = "%<\\AcObjProp Object(%<\\_ObjId " + strObjId + ">%).IsDynamicBlock \\f \"%bl2\">%";
                            //tb.SetTextString(i, 4, "%<\\AcObjProp Object(%<\\_ObjId " + strObjId + ">%).IsDynamicBlock \\f \"%bl2\">%");
                           
                            tb.SetAlignment(i, 4, CellAlignment.MiddleCenter);
                        }
                    }
                    //非常重要,根据当前样式更新表格,不加此句,会导致AutoCAD崩溃
                    tb.GenerateLayout();
                    //tb.FlowDirection = Autodesk.AutoCAD.DatabaseServices.FlowDirection.TopToBottom;
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    btr.AppendEntity(tb);
                    tr.AddNewlyCreatedDBObject(tb, true);
                    tr.Commit();
                }
            }
        }

        [CommandMethod("t8")]
        public static void t8()//选择table,读取属性
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            Table myTable = new Table();
            PromptEntityOptions opts = new PromptEntityOptions("\n选择一个table:");
            opts.SetRejectMessage("错误的选择!");
            opts.AddAllowedClass(typeof(Table), false);
            PromptEntityResult res = ed.GetEntity(opts);
            if (res.Status != PromptStatus.OK)
                return;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                myTable = tr.GetObject(res.ObjectId, OpenMode.ForRead) as Table;
                myTable.FlowDirection = FlowDirection.LeftToRight;
                tr.Commit();
            }
        }

    }
}

 楼主| 发表于 2020-5-17 16:22 | 显示全部楼层
注意要先在自己的图纸中定义块,否则将块加入表格会出错
发表于 2020-5-18 18:15 | 显示全部楼层
本帖最后由 zixuan203344 于 2020-5-18 18:16 编辑

分享精神赞一个
不过确实如此,因为CAD自带表格有点……鸡肋,所以大家都不怎么喜欢CAD自带的表格,还是excel表格好用,计算修改都很方便,需要CAD表格,直接导进来。
发表于 2020-5-22 01:30 | 显示全部楼层
表示不知道怎么用
您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|CAD论坛|CAD教程|CAD下载|联系我们|关于明经|明经通道 ( 粤ICP备05003914号 )  
©2000-2023 明经通道 版权所有 本站代码,在未取得本站及作者授权的情况下,不得用于商业用途

GMT+8, 2024-6-15 07:52 , Processed in 0.419460 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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