使用netdxf(C#)框架实现dxf文件读取与导出坐标

这篇具有很好参考价值的文章主要介绍了使用netdxf(C#)框架实现dxf文件读取与导出坐标。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

使用netdxf(C#)框架实现dxf文件读取与导出坐标

一、新建窗体应用程序DxfToolDemo,将默认的Form1重命名为FormDxfTool

窗体FormDxfTool.Designer.cs设计器源程序如下:


namespace DxfToolDemo
{
    partial class FormDxfTool
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.rtxtMessage = new System.Windows.Forms.RichTextBox();
            this.btnOpenDxf = new System.Windows.Forms.Button();
            this.btnExportCsv = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // rtxtMessage
            // 
            this.rtxtMessage.Location = new System.Drawing.Point(12, 70);
            this.rtxtMessage.Name = "rtxtMessage";
            this.rtxtMessage.Size = new System.Drawing.Size(1102, 529);
            this.rtxtMessage.TabIndex = 0;
            this.rtxtMessage.Text = "";
            // 
            // btnOpenDxf
            // 
            this.btnOpenDxf.Font = new System.Drawing.Font("宋体", 15F);
            this.btnOpenDxf.Location = new System.Drawing.Point(23, 12);
            this.btnOpenDxf.Name = "btnOpenDxf";
            this.btnOpenDxf.Size = new System.Drawing.Size(127, 43);
            this.btnOpenDxf.TabIndex = 1;
            this.btnOpenDxf.Text = "打开Dxf文件";
            this.btnOpenDxf.UseVisualStyleBackColor = true;
            this.btnOpenDxf.Click += new System.EventHandler(this.btnOpenDxf_Click);
            // 
            // btnExportCsv
            // 
            this.btnExportCsv.Font = new System.Drawing.Font("宋体", 15F);
            this.btnExportCsv.Location = new System.Drawing.Point(185, 12);
            this.btnExportCsv.Name = "btnExportCsv";
            this.btnExportCsv.Size = new System.Drawing.Size(182, 43);
            this.btnExportCsv.TabIndex = 2;
            this.btnExportCsv.Text = "导出坐标为.CSV";
            this.btnExportCsv.UseVisualStyleBackColor = true;
            this.btnExportCsv.Click += new System.EventHandler(this.btnExportCsv_Click);
            // 
            // FormDxfTool
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1126, 611);
            this.Controls.Add(this.btnExportCsv);
            this.Controls.Add(this.btnOpenDxf);
            this.Controls.Add(this.rtxtMessage);
            this.Name = "FormDxfTool";
            this.Text = "Dxf转化工具【CAD文件转坐标】";
            this.Load += new System.EventHandler(this.FormDxfTool_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.RichTextBox rtxtMessage;
        private System.Windows.Forms.Button btnOpenDxf;
        private System.Windows.Forms.Button btnExportCsv;
    }
}

二、右键 项目DxfToolDemo, 管理NuGet程序包,输入关键字netDxf,下载该程序包

使用netdxf(C#)框架实现dxf文件读取与导出坐标,Dxf,netDxf,Dxf文件转化坐标,c#,Dxf工具,CAD图纸导出坐标

三、netDxf框架关键类型说明:

关键结构 netDxf.Vector3
            可以认为是立体三维坐标(x,y,z)
关键结构 netDxf.Vector2
            可以认为是平面二维坐标(x,y)

DxfDocument用于读写dxf文件

      关键函数Load()用于加载文件

      添加实体:dxfDocument.Entities.Add(EntityObject entity);

      关键函数Save()用于保存文件 

关键属性: Entities: 对应类型 netDxf.Collections.DrawingEntities

密封类DrawingEntities由一系列【点、线、圆等】集合组成,允许直接访问与图形中实体相关的操作

对应的各种实体EntityObject说明:
netDxf.Entities.EntityObject:
        Gets the complete list entities contained in the active layout.
        抽象类,以下所有实体对象的父类

netDxf.Entities.PolyfaceMesh:
    Represents a polyface mesh entity.

netDxf.Entities.Text:
    Gets the list of texts in the active layout.
           
 netDxf.Entities.MText:       
     Gets the list of multiline texts in the active layout.

 netDxf.Entities.Hatch:       
     Gets the list of hatches in the active layout.

 netDxf.Entities.Image:     
     Gets the list of images in the active layout.
 
netDxf.Entities.Mesh:      
        Gets the list of mesh in the active layout.
 
netDxf.Entities.Leader:        
        Gets the list of leader in the active layout.
             
netDxf.Entities.Point:
        Gets the list of points in the active layout.
        
netDxf.Entities.Tolerance:
        Gets the list of tolerance in the active layout.
        
netDxf.Entities.MLine:
        Gets the list of multilines in the active layout.
        
netDxf.Entities.Dimension:
        Gets the list of dimensions in the active layout.
        
netDxf.Entities.Spline:
        Gets the list of splines in the active layout.
         
netDxf.Entities.Ray:
        Gets the list of rays in the active layout.

netDxf.Entities.Viewport:        
        Gets the list of viewports in the active layout.

netDxf.Entities.XLine:
        Gets the list of extension lines in the active layout.
        
netDxf.Entities.Underlay:
        Gets the list of underlay in the active layout.
       
netDxf.Entities.PolygonMesh:
        Gets the list of polygon meshes in the active layout.

netDxf.Entities.AttributeDefinition:
        Gets the list of attribute definitions in the active layout.

netDxf.Entities.Polyline3D:
        Gets the list of polylines in the active layout.

netDxf.Entities.Arc:
        Gets the list of arcs contained in the active layout. 

netDxf.Entities.Ellipse:
        Gets the list of ellipses in the active layout.

netDxf.Entities.Wipeout:
        Gets the list of wipeouts in the active layout. 

netDxf.Entities.Face3D:
        Gets the list of 3d faces in the active layout.

netDxf.Entities.Circle:
        Gets the list of circles in the active layout.

netDxf.Entities.Trace:
        Gets the list of traces in the active layout.

netDxf.Entities.Insert:
        Gets the list of inserts in the active layout.

netDxf.Entities.Line:
        Gets the list of lines in the active layout.

netDxf.Entities.Shape:
        Gets the list of shapes in the active layout.

netDxf.Entities.Polyline2D:
        Gets the list of polylines in the active layout.

netDxf.Entities.Solid:
        Gets the list of solids in the active layout.

四、新建csv导出类CsvUtil,

CsvUtil.cs源程序如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DxfToolDemo
{
    public class CsvUtil
    {
        /// <summary>
        /// 写CSV日志 按列显示
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="coordList">元组:圆心坐标,半径,模板名</param>
        /// <returns></returns>
        public static bool WriteCoordinateLogCsv(string fileName, List<Tuple<netDxf.Vector3, double, string>> coordList)
        {
            if (coordList == null || coordList.Count == 0) 
            {
                return false;
            }
            try
            {
                string directoryPath = Path.GetDirectoryName(fileName);
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }
                string columnContents = "模板名,极柱序号,圆心X坐标,圆心Y坐标,圆心Z坐标,圆心半径\r\n";
                if (!File.Exists(fileName))
                {
                    File.AppendAllText(fileName, columnContents, Encoding.Default);
                }

                StringBuilder sb = new StringBuilder();
                using (StreamWriter write = new StreamWriter(fileName, true, Encoding.Default))
                {
                    for (int i = 0; i < coordList.Count; i++)
                    {
                        sb = new StringBuilder();
                        sb.Append($"{ProcessPunctuationForCsv(coordList[i].Item3)},");
                        sb.Append($"{i + 1},");
                        sb.Append($"{coordList[i].Item1.X},");
                        sb.Append($"{coordList[i].Item1.Y},");
                        sb.Append($"{coordList[i].Item1.Z},");
                        sb.Append($"{coordList[i].Item2}");
                        write.WriteLine(sb.ToString());
                    }                    
                }
                return true;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("CSV文件写入失败:" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 处理csv文件中的双引号和逗号,使其在Excel中完美显示为一个单元格
        /// 斯内科
        /// </summary>
        /// <param name="srcStr"></param>
        /// <returns></returns>
        private static string ProcessPunctuationForCsv(string srcStr)
        {
            if (srcStr == null)
            {
                return string.Empty;
            }
            bool quoteFlag = false;//是否添加过双引号
            //如果存在双引号,需要将字符串的一个双引号 替换为 两个双引号。并且需要在字符串的前后加上双引号
            if (srcStr.Contains("\""))
            {
                srcStr = srcStr.Replace("\"", "\"\"");
                srcStr = "\"" + srcStr + "\"";
                quoteFlag = true;
            }
            //如果只存在逗号(不存在引号),将前后加引号即可
            if (srcStr.Contains(",") && !quoteFlag)
            {
                srcStr = "\"" + srcStr + "\"";
            }
            return srcStr;
        }
    }
}

五、窗体程序如下:

FormDxfTool.cs源程序:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using netDxf;
using netDxf.Collections;
using netDxf.Entities;

namespace DxfToolDemo
{
    public partial class FormDxfTool : Form
    {
        public FormDxfTool()
        {
            InitializeComponent();
            rtxtMessage.ReadOnly = true;            
        }

        /// <summary>
        /// 显示推送消息
        /// </summary>
        /// <param name="msg"></param>
        private void DisplayMessage(string msg)
        {
            this.BeginInvoke(new Action(() =>
            {
                if (rtxtMessage.TextLength > 20480)
                {
                    rtxtMessage.Clear(); 
                }
                rtxtMessage.AppendText($"{DateTime.Now.ToString("HH:mm:ss.fff")}->{msg}\n");
                rtxtMessage.ScrollToCaret();
            }));
        }

        private void btnOpenDxf_Click(object sender, EventArgs e)
        {
            rtxtMessage.Clear();
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
            openFileDialog.Filter = "dxf|*.dxf|All|*.*";
            DialogResult dialog = openFileDialog.ShowDialog();
            if (dialog != DialogResult.OK)
            {
                return;
            }
            string fileName = openFileDialog.FileName;//AppDomain.CurrentDomain.BaseDirectory + "testFile\\蓝本-CAD.dxf"
            DisplayMessage($"CAD文件dxf路径为【{fileName}】");
            DxfDocument dxfDocument = DxfDocument.Load(fileName);
            DisplayMessage($"活动布局的名称为【{dxfDocument.Entities.ActiveLayout}】");
            rtxtMessage.Tag = dxfDocument.Entities;
            IEnumerable<Circle> circles = dxfDocument.Entities.Circles;
            int circleCount = circles.Count();
            DisplayMessage($"读取到圆Circle的个数为【{circleCount}】");
            for (int i = 0; i < circleCount; i++)
            {
                Circle circle = circles.ElementAt(i);
                DisplayMessage($"\x20\x20圆【{(i + 1).ToString("D3")}】,圆心坐标【({circle.Center})】,半径【{circle.Radius}】");
            }            
        }

        private void btnExportCsv_Click(object sender, EventArgs e)
        {
            DrawingEntities drawingEntities = rtxtMessage.Tag as DrawingEntities;
            if (drawingEntities == null) 
            {
                return;
            }
            List<Tuple<Vector3, double, string>> coordList = new List<Tuple<Vector3, double, string>>();
            IEnumerable<Circle> circles = drawingEntities.Circles;
            int circleCount = circles.Count();//找出所有的圆
            for (int i = 0; i < circleCount; i++)
            {
                Circle circle = circles.ElementAt(i);
                //元组:圆心坐标,半径,活动设计名
                coordList.Add(Tuple.Create(circle.Center, circle.Radius, drawingEntities.ActiveLayout));
            }
            string fileName = AppDomain.CurrentDomain.BaseDirectory + "testFile\\蓝本.csv";
            bool result = CsvUtil.WriteCoordinateLogCsv(fileName, coordList);
            MessageBox.Show($"导出csv文件结果【{result}】\n路径:{fileName}");
        }

        private void FormDxfTool_Load(object sender, EventArgs e)
        {
            /*
             * 1、读取dxf文件的思路
新建DxfDocument对象-调用Load方法读取对应地址的dxf文件并保存在新建的DxfDocument对象中-从新建的DxfDocument对象中读取对应的元素
读取dxf文件:
DxfDocument dxf = DxfDocument.Load("蓝本.dxf");

关键结构 netDxf.Vector3
            可以认为是立体三维坐标(x,y,z)
关键结构 netDxf.Vector2
            可以认为是平面二维坐标(x,y)
 读取文件中的核心属性:
Entities:
对应类型 netDxf.Collections.DrawingEntities
            密封类DrawingEntities由一系列【点、线、圆等】集合组成,允许直接访问与图形中实体相关的操作
netDxf.Entities.EntityObject:
        Gets the complete list entities contained in the active layout.
        抽象类,以下所有实体对象的父类

netDxf.Entities.PolyfaceMesh:
    Represents a polyface mesh entity.

netDxf.Entities.Text:
    Gets the list of texts in the active layout.
           
 netDxf.Entities.MText:       
     Gets the list of multiline texts in the active layout.

 netDxf.Entities.Hatch:       
     Gets the list of hatches in the active layout.

 netDxf.Entities.Image:     
     Gets the list of images in the active layout.
 
netDxf.Entities.Mesh:      
        Gets the list of mesh in the active layout.
 
netDxf.Entities.Leader:        
        Gets the list of leader in the active layout.
             
netDxf.Entities.Point:
        Gets the list of points in the active layout.
        
netDxf.Entities.Tolerance:
        Gets the list of tolerance in the active layout.
        
netDxf.Entities.MLine:
        Gets the list of multilines in the active layout.
        
netDxf.Entities.Dimension:
        Gets the list of dimensions in the active layout.
        
netDxf.Entities.Spline:
        Gets the list of splines in the active layout.
         
netDxf.Entities.Ray:
        Gets the list of rays in the active layout.

netDxf.Entities.Viewport:        
        Gets the list of viewports in the active layout.

netDxf.Entities.XLine:
        Gets the list of extension lines in the active layout.
        
netDxf.Entities.Underlay:
        Gets the list of underlay in the active layout.
       
netDxf.Entities.PolygonMesh:
        Gets the list of polygon meshes in the active layout.

netDxf.Entities.AttributeDefinition:
        Gets the list of attribute definitions in the active layout.

netDxf.Entities.Polyline3D:
        Gets the list of polylines in the active layout.

netDxf.Entities.Arc:
        Gets the list of arcs contained in the active layout. 

netDxf.Entities.Ellipse:
        Gets the list of ellipses in the active layout.

netDxf.Entities.Wipeout:
        Gets the list of wipeouts in the active layout. 

netDxf.Entities.Face3D:
        Gets the list of 3d faces in the active layout.

netDxf.Entities.Circle:
        Gets the list of circles in the active layout.

netDxf.Entities.Trace:
        Gets the list of traces in the active layout.

netDxf.Entities.Insert:
        Gets the list of inserts in the active layout.

netDxf.Entities.Line:
        Gets the list of lines in the active layout.

netDxf.Entities.Shape:
        Gets the list of shapes in the active layout.

netDxf.Entities.Polyline2D:
        Gets the list of polylines in the active layout.

netDxf.Entities.Solid:
        Gets the list of solids in the active layout.            
            */
        }
    }
}

六、运行效果如图:

【获取所有半径为3的圆极柱】

导出csv

使用netdxf(C#)框架实现dxf文件读取与导出坐标,Dxf,netDxf,Dxf文件转化坐标,c#,Dxf工具,CAD图纸导出坐标 文章来源地址https://www.toymoban.com/news/detail-794149.html

到了这里,关于使用netdxf(C#)框架实现dxf文件读取与导出坐标的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C#使用MiniExcel导入导出数据到Excel/CSV文件

    MiniExcel简介 简单、高效避免OOM的.NET处理Excel查、写、填充数据工具。 目前主流框架大多需要将数据全载入到内存方便操作,但这会导致内存消耗问题,MiniExcel 尝试以 Stream 角度写底层算法逻辑,能让原本1000多MB占用降低到几MB,避免内存不够情况。 特点: 低内存耗用,避免

    2024年02月19日
    浏览(32)
  • 【办公软件】C#调用NPOI实现Excel文件的加载、导出功能

    本文将介绍如何使用C#和NPOI库实现Excel文件的读写操作,并通过加载文件和导出文件的按钮进行封装。NPOI是一个强大的.NET库,可以轻松处理Excel文件。我们将学习如何使用NPOI打开现有的Excel文件、读取数据,并将数据写入到Excel文件中。 在开始之前,请确保已安装以下环境:

    2024年02月06日
    浏览(41)
  • 设置Solidworks导出文件的坐标系,stl坐标系平移

    在OpenGL中使用导出的stl模型时发现坐标系不在原点: 使用solidworks 打开这个stl,发现果然不对  不满意,必须改过来!!! 首先打开solidworks原文件 新建坐标系   建立完成---坐标系1    输出时点击-选项  输出坐标系--坐标系1  然后保存就完成了。 再看看    end 上边方法复

    2024年02月11日
    浏览(84)
  • Word控件Aspose.Words教程:使用 C# 读取 SXC 和 FODS 文件

    Aspose.Words是一种高级Word文档处理API,用于执行各种文档管理和操作任务。API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft Word。 Aspose支持流行文件格式处理,并允许将各类文档导出或转换为固定布局文件格式和最常用的图像/多媒体格

    2024年02月10日
    浏览(37)
  • C#【必备技能篇】使用NPOI实现对excel的读取和写入

    依次执行下图中的1-6按钮 , 可以通过查看程序文件夹中的excel文件来加深理解。 链接:https://pan.baidu.com/s/19PgQMhCKviw9aBAjmJHSww 提取码:2omi 需要在源码中增加如下引用。相应的dll已更新到 5 的下载地址中。

    2023年04月13日
    浏览(29)
  • 搭建GDAL JAVA环境;DXF转KML;坐标转换;PROJ: proj_create_from_database 错误解决

    GDAL是一个栅格和矢量地理空间数据格式的转换库,由开源地理空间基金会按照MIT开源协议发布。作为一个库,它向应用程序为所有支持的数据格式提供统一的栅格抽象数据模型和矢量抽象数据模型。它还提供了用于数据转换和处理的各种有用的命令行实用工具。 GDAL官网:

    2024年02月05日
    浏览(40)
  • C# 使用NModbus4进行TCP读取,并且实现自动断线重连

    C# 使用NModbus4进行TCP读取,并且实现自动断线重连

    2024年02月09日
    浏览(34)
  • 045:Vue读取本地上传JSON文件,导出JSON文件方法

    第045个 查看专栏目录: VUE ------ element UI 在vue和element UI联合技术栈的操控下,本专栏提供行之有效的源代码示例和信息点介绍,做到灵活运用。 (1)提供vue2的一些基本操作:安装、引用,模板使用,computed,watch,生命周期(beforeCreate,created,beforeMount,mounted, beforeUpdate,upda

    2024年02月04日
    浏览(38)
  • 【Spring】1、Spring 框架的基本使用【读取配置文件、IoC、依赖注入的几种方式、FactoryBean】

    Spring 框架可以说是 Java 开发中最重要的框架,功能 非常 强大 中文文档:https://springdoc.cn/spring/ 官网:https://spring.io/ Spring makes Java Simple、modern、productive … Spring 框架的几个核心概念: IoC: I nversion o f C ontrol:控制反转 DI: D ependency I njection:依赖注入 AOP: A spect O riented P rogram

    2024年02月09日
    浏览(36)
  • dxf文件用什么打开(dxf文件格式介绍)

    很多机械设计小伙伴日常工作都会接触到dxf文件,那么dxf是什么文件格式呢?以及dxf文件用什么打开?相信这都是很多机械设计小伙伴关心的问题,接下来小编就来跟大家讲解一下。 DXF文件是一种广泛使用的CAD数据文件格式,它可以使不同软件之间的CAD数据交换更加方便。

    2024年02月05日
    浏览(67)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包