.NET

Reply
Mentor
santoshr0114
Posts: 183
Registered: ‎03-21-2012
Message 1 of 16 (2,011 Views)
Accepted Solution

Data Extraction Using .Net

2011 Views, 15 Replies
06-18-2012 04:08 AM

Hi Guys,

 

I need to extract data from AutoCad Drawing using C# or VB.Net.

 

I have a Title Block which is not inserted using attributes. It has some horizontal & vertical lines drawn  to look like a table and text added between them. See the attchment.

 

I need to extract data from that and display in Ms-Excel or in a datagridview.

 

Does anybody know how to do it ?????

It would be very helpful.

 

Thank You

Regards
Santosh

Something wrong with your drawing, there are too many invisible texts,

see complete code:

using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Interop.Common;
using Autodesk.AutoCAD.Interop;
using acApp = Autodesk.AutoCAD.ApplicationServices.Application;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
// This line is not mandatory, but improves loading performances
[assembly: CommandClass(typeof(AutoCAD_CSharp_plug_in1.ExcelReport))]
namespace AutoCAD_CSharp_plug_in1
{
class ExcelReport
{
[CommandMethod("xlrep")]
public static void TextSelectToExcel()
{
string title = "";
string jobno = "";
List<string> alltexts = new List<string>();
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
Database db = doc.Database;
string xlFileName = (string)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("dwgprefix");
string dwgname = (string)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("dwgname");
dwgname = dwgname.Substring(0, dwgname.Length - 4) + ".xlsx";
xlFileName = Path.Combine(xlFileName, dwgname);
Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);
try
{
using (Transaction tr = db.TransactionManager.StartTransaction())
{
PromptPointOptions ppo = new PromptPointOptions("\nSelect a first corner of table: ");
PromptPointResult ppr = ed.GetPoint(ppo);
if (ppr.Status != PromptStatus.OK) return;
PromptCornerOptions pco = new PromptCornerOptions("\nOther corner: ", ppr.Value);
PromptPointResult pcr = ed.GetCorner(pco);
if (pcr.Status != PromptStatus.OK) return;
Point3d p1 = ppr.Value;
Point3d p2 = pcr.Value;
if (p1.X == p2.X || p1.Y == p2.Y)
{
ed.WriteMessage("\nInvalid coordinate specification");
return;
}
TypedValue[] tvs = new TypedValue[]
{new TypedValue(0, "text")
};
SelectionFilter filter = new SelectionFilter(tvs);
PromptSelectionResult result = ed.SelectCrossingWindow(p1, p2, filter);
if (result.Status != PromptStatus.OK) return;
Dictionary<Point3d, string> txtlist = new Dictionary<Point3d, string>();
foreach (SelectedObject selobj in result.Value)
{
DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead) as DBObject;
DBText txt = obj as DBText;
if (txt != null)
{
string strtext = txt.TextString;
Point3d pp = txt.Position;
if (!txtlist.ContainsKey(pp))
txtlist.Add(pp, strtext);
}
}
List<Point3d> ptlist = new List<Point3d>(txtlist.Keys);
ptlist.Sort(delegate(Point3d pa, Point3d pb)
{ return (pa.Y.CompareTo(pb.Y)); });
ptlist.Reverse();
title = txtlist[ptlist[6]];
jobno = txtlist[ptlist[5]];
Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format
("Title: {0}\nJob No.: {1}", title, jobno));
//---------------------------------------------------------------------------//
PromptSelectionResult result2 = ed.SelectAll(filter);
if (result2.Status != PromptStatus.OK) return;
foreach (SelectedObject selobj2 in result2.Value)
{
DBObject obj = tr.GetObject(selobj2.ObjectId, OpenMode.ForRead) as DBObject;
DBText txt2 = obj as DBText;
if (txt2 != null)
{
string strtext = txt2.TextString;
if (strtext!=string.Empty)
alltexts.Add(strtext);
}
}
}
//---------------------------------------------------------------------------//
Excel.Application xlApp;
Excel.Workbooks xlBooks;
Excel.Workbook xlBook;
Excel.Sheets xlSheets;
Excel.Worksheet xlSheet;
Excel.Range xlRange;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlApp.SheetsInNewWorkbook = 1;
xlApp.Workbooks.Add(Type.Missing);
xlBooks = (Excel.Workbooks)xlApp.Workbooks;
xlBook = (Excel.Workbook)xlBooks[1];
xlBook.Saved = true;
xlApp.DisplayAlerts = false;
xlSheets = (Excel.Sheets)xlBook.Worksheets;
xlSheet = (Excel.Worksheet)xlSheets.get_Item(1);
xlRange = (Excel.Range)xlSheet.Range["A1"];
xlRange.ColumnWidth = 20;
xlRange.NumberFormat = "@";
int row = 1;
xlRange.Cells[row, 1] = title;
row = 1;
xlRange = (Excel.Range)xlSheet.Range["B1"];
xlRange.ColumnWidth = 20;
xlRange.NumberFormat = "@";
xlRange.Cells[row, 1] = jobno;
xlRange = (Excel.Range)xlSheet.Range["A2"];
int r = 1;
foreach (string s in alltexts)
{
xlRange.Cells[r, 1] = s;
r += 1;
}
//Save workbook
xlBook.SaveAs(xlFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlApp.Workbooks.Close();
xlApp.Quit();
//or
// xlApp.Windows[1].Close(false, Type.Missing, Type.Missing);
}
catch (System.Exception ex)
{
Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(
"\n{0}", ex.Message);
}
finally
{
Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Remove blank rows from Excel file manually");
}
}
}
}

 

~'J'~

Distinguished Contributor
HJohn1
Posts: 170
Registered: ‎09-26-2008
Message 2 of 16 (1,986 Views)

Re: Data Extraction Using .Net

06-18-2012 06:03 AM in reply to: santoshr0114

Personally I think that using attributes is more efficient than using plain text.  You can more easilly create a routine to select the block containing the attributes and also since you would know what data type is expected on each attribute validate it before you extract it.  There are many sample around on how to create selection sets, extract attributes, etc.

*Expert Elite*
Hallex
Posts: 1,569
Registered: ‎10-08-2008
Message 3 of 16 (1,972 Views)

Re: Data Extraction Using .Net

06-18-2012 08:02 AM in reply to: santoshr0114

Upload your drawing with this block (< A2010),

maybe I can help

 

~'J'~

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Valued Mentor
AubelecBE
Posts: 394
Registered: ‎01-27-2010
Message 4 of 16 (1,943 Views)

Re: Data Extraction Using .Net

06-19-2012 03:39 AM in reply to: Hallex

hi you can't extract plain text from a block. You have to use attribut.

 

Autocad have a subroutine for extract attribut. No need à code vb.net for doing this.

 

 

++

*Expert Elite*
Hallex
Posts: 1,569
Registered: ‎10-08-2008
Message 5 of 16 (1,951 Views)

Re: Data Extraction Using .Net

06-19-2012 03:43 AM in reply to: AubelecBE

Sorry, but I can to do it easy,the same way as for constant attributes

using BlockTableRecord's ObjectIds of this BlockReference

 

~'J'~

 

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Mentor
santoshr0114
Posts: 183
Registered: ‎03-21-2012
Message 6 of 16 (1,931 Views)

Re: Data Extraction Using .Net

06-19-2012 11:07 PM in reply to: santoshr0114

Hi,

 

Sorry for the delay in uploading the drawing file(.dwg).

 

 

First Task:

 

I need to extract all the text from the drawing using C# or VB.Net and display it in notepad or excel file.

 

Second Task:

 

I have to fetch only the text data from the left bottom corner(BOM) and the right bottom corner(Title Block) in the same format as it is displayed i autocad drawing and send it to excel.

 

Please let me know how to do it...

 

 

 

Regards
Santosh
*Expert Elite*
Hallex
Posts: 1,569
Registered: ‎10-08-2008
Message 7 of 16 (1,925 Views)

Re: Data Extraction Using .Net

06-20-2012 01:29 AM in reply to: santoshr0114

In other words you want to retrive:

"AP-0298" and "Sample"

Or I'm wrong?

 

You wrote

>>I need to extract all the text from the drawing using C# or VB.Net and display it in notepad or excel file.

 

Just the text only or you need to get mtext as well?

 

~'J'~

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Mentor
santoshr0114
Posts: 183
Registered: ‎03-21-2012
Message 8 of 16 (1,919 Views)

Re: Data Extraction Using .Net

06-20-2012 04:04 AM in reply to: santoshr0114

Hallex,

 

Yes...

Regards
Santosh
*Expert Elite*
Hallex
Posts: 1,569
Registered: ‎10-08-2008
Message 9 of 16 (1,913 Views)

Re: Data Extraction Using .Net

06-20-2012 06:22 AM in reply to: santoshr0114

Something wrong with your drawing, there are too many invisible texts,

see complete code:

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

using System.Collections.Generic;
using System.Runtime.InteropServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Interop.Common;
using Autodesk.AutoCAD.Interop;
using acApp = Autodesk.AutoCAD.ApplicationServices.Application;

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

// This line is not mandatory, but improves loading performances
[assembly: CommandClass(typeof(AutoCAD_CSharp_plug_in1.ExcelReport))]

namespace AutoCAD_CSharp_plug_in1
{
    class ExcelReport
    {
        [CommandMethod("xlrep")]
        public static void TextSelectToExcel()
        {
            string title = "";
            string jobno = "";
            List<string> alltexts = new List<string>();

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            string xlFileName = (string)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("dwgprefix");
            string dwgname = (string)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("dwgname");
            dwgname = dwgname.Substring(0, dwgname.Length - 4) + ".xlsx";
            xlFileName = Path.Combine(xlFileName, dwgname);

            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);
            try
            {
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                PromptPointOptions ppo = new PromptPointOptions("\nSelect a first corner of table: ");
                PromptPointResult ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;
                PromptCornerOptions pco = new PromptCornerOptions("\nOther corner: ", ppr.Value);
                PromptPointResult pcr = ed.GetCorner(pco);
                if (pcr.Status != PromptStatus.OK) return;
                Point3d p1 = ppr.Value;
                Point3d p2 = pcr.Value;
                if (p1.X == p2.X || p1.Y == p2.Y)
                {
                    ed.WriteMessage("\nInvalid coordinate specification");
                    return;
                }
                TypedValue[] tvs = new TypedValue[]
            {new TypedValue(0, "text")

            };
                SelectionFilter filter = new SelectionFilter(tvs);

                PromptSelectionResult result = ed.SelectCrossingWindow(p1, p2, filter);
                if (result.Status != PromptStatus.OK) return;
                Dictionary<Point3d, string> txtlist = new Dictionary<Point3d, string>();

                foreach (SelectedObject selobj in result.Value)
                {

                    DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead) as DBObject;
                    DBText txt = obj as DBText;
                    if (txt != null)
                    {
                        string strtext = txt.TextString;
                        Point3d pp = txt.Position;
                        if (!txtlist.ContainsKey(pp))
                            txtlist.Add(pp, strtext);
                    }

                }

                List<Point3d> ptlist = new List<Point3d>(txtlist.Keys);

                ptlist.Sort(delegate(Point3d pa, Point3d pb)
                { return (pa.Y.CompareTo(pb.Y)); });

                ptlist.Reverse();

                title = txtlist[ptlist[6]];
                jobno = txtlist[ptlist[5]];

                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format
                ("Title: {0}\nJob No.: {1}", title, jobno));

                //---------------------------------------------------------------------------//

                PromptSelectionResult result2 = ed.SelectAll(filter);

                if (result2.Status != PromptStatus.OK) return;



                foreach (SelectedObject selobj2 in result2.Value)
                {

                    DBObject obj = tr.GetObject(selobj2.ObjectId, OpenMode.ForRead) as DBObject;
                    DBText txt2 = obj as DBText;
                    if (txt2 != null)
                    {
                        string strtext = txt2.TextString;
                       if (strtext!=string.Empty)
                        alltexts.Add(strtext);
                    }

                }



            }

            //---------------------------------------------------------------------------//
            Excel.Application xlApp;
            Excel.Workbooks xlBooks;
            Excel.Workbook xlBook;
            Excel.Sheets xlSheets;
            Excel.Worksheet xlSheet;
            Excel.Range xlRange;
          
                xlApp = new Excel.Application();

                xlApp.Visible = false;

                xlApp.SheetsInNewWorkbook = 1;

                xlApp.Workbooks.Add(Type.Missing);

                xlBooks = (Excel.Workbooks)xlApp.Workbooks;
                xlBook = (Excel.Workbook)xlBooks[1];
                xlBook.Saved = true;
                xlApp.DisplayAlerts = false;


                xlSheets = (Excel.Sheets)xlBook.Worksheets;
                xlSheet = (Excel.Worksheet)xlSheets.get_Item(1);

                xlRange = (Excel.Range)xlSheet.Range["A1"];
                xlRange.ColumnWidth = 20;
                xlRange.NumberFormat = "@";
                int row = 1;
                xlRange.Cells[row, 1] = title;

                row = 1;

                xlRange = (Excel.Range)xlSheet.Range["B1"];
                xlRange.ColumnWidth = 20;
                xlRange.NumberFormat = "@";
                xlRange.Cells[row, 1] = jobno;

                xlRange = (Excel.Range)xlSheet.Range["A2"];
                int r = 1;
                foreach (string s in alltexts)
                {
                    xlRange.Cells[r, 1] = s;
                    r += 1;
                }
         
                //Save workbook
                xlBook.SaveAs(xlFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                xlApp.Workbooks.Close();
                xlApp.Quit();
                //or
                // xlApp.Windows[1].Close(false, Type.Missing, Type.Missing);
            }
            catch (System.Exception ex)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(
                    "\n{0}", ex.Message);
            }
            finally
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Remove blank rows from Excel file manually");
            }
        }
    }
}

 

~'J'~

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Mentor
santoshr0114
Posts: 183
Registered: ‎03-21-2012
Message 10 of 16 (1,904 Views)

Re: Data Extraction Using .Net

06-20-2012 08:04 AM in reply to: santoshr0114

Hallex,

 

Thank You.

 

I will try using this, but i think it asks for user to select some objects.

 

Let me try this now...

 

Regards
Santosh
Post to the Community

Have questions about Autodesk products? Ask the community.

New Post
Need installation help?

Start with some of our most frequented solutions or visit the Installation and Licensing Forum to get help installing your software.