公司来了一批图纸,里面有一部分内容需要复制到excel中,几百张来图每一张都
手工复制,烦死了。编写一个CAD插件,自动导出文本,简单记录在下面。
想法是:
1.输入命令,选择所有dwg文件
2.挨个处理dwg文件,生成同名的txt文件保存文本
基本思路是用Database.ReadDwgFile 读取dwg文件,因为这样可以不用显示文档,可以提高速度;
[CommandMethod("GetText")] public void GetTextCST() { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "dwg files (*.dwg)|*.dwg|All files (*.*)|*.*"; ofd.FilterIndex = 1; ofd.RestoreDirectory = true; ofd.Multiselect = true; if(ofd.ShowDialog()== DialogResult.OK) foreach (string fn in ofd.FileNames) try { DoDwg2Csv(fn); } catch { File.AppendAllText("D:\dwg2csv.txt", DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + fn + " "); } }
private void DoDwg2Csv(string fn) { string csvname = fn + ".csv"; using (Database db = new Database(false, true)) { db.ReadDwgFile(fn, FileOpenMode.OpenForReadAndAllShare, false, ""); db.CloseInput(true); using (Transaction tr = db.TransactionManager.StartTransaction()) { // 模型空间 BlockTable blkTbl = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord modelSpace = tr.GetObject( blkTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; // 遍历模型空间,提取文字 List<DBText> txts = new List<DBText>(); foreach (ObjectId oid in modelSpace) { DBObject dbobj = tr.GetObject(oid, OpenMode.ForRead); if (dbobj is Entity) { Entity entity = dbobj as Entity; string enttype = entity.GetRXClass().Name; if (enttype == "AcDbText") { DBText acText = entity as DBText; if (acText.Position.X < 587 || acText.Position.Y < 115)//指定范围 continue; txts.Add( acText ); } }//if (dbobj is Entity) }//foreach (ObjectId oid in modelSpace) txts.Sort((t1, t2) => t1.Position.X >= t2.Position.X ? 1 : -1); for (int i = 0; i < txts.Count;i++) File.AppendAllText(csvname, txts[i].TextString+" ", Encoding.Default); }//using }//using }