使用netdxf(C#)框架實現(xiàn)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框架關鍵類型說明:
關鍵結構 netDxf.Vector3
? ? ? ? ? ? 可以認為是立體三維坐標(x,y,z)
關鍵結構 netDxf.Vector2
? ? ? ? ? ? 可以認為是平面二維坐標(x,y)
DxfDocument用于讀寫dxf文件
? ? ? 關鍵函數(shù)Load()用于加載文件
? ? ? 添加實體:dxfDocument.Entities.Add(EntityObject entity);
? ? ? 關鍵函數(shù)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的個數(shù)為【{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文章來源:http://www.zghlxwxcb.cn/news/detail-794149.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-794149.html
到了這里,關于使用netdxf(C#)框架實現(xiàn)dxf文件讀取與導出坐標的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!