c# cad二次开发通过获取excel数据 在CAD绘图,将CAD属性导出到excel

news/2024/6/30 8:11:26

c# cad二次开发通过获取excel数据 在CAD绘图,将CAD属性导出到excel
using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = NetOffice.ExcelApi;
using Autodesk.AutoCAD.DatabaseServices;
using System.IO;
using Autodesk.AutoCAD.Geometry;
namespace _17外部文件_Excel_交互
{
public class Class1
{
public struct CircleData
{
public double X;
public double Y;
public double Z;
public double R;
}

[CommandMethod(“ExcelDemo”)]
public void ExcelDemo()
{
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
#region 保存图形信息到Excel文件
//string fileName = this.OpenSaveDialog(ed, db);
//if (fileName == “”) return;
获取图形信息
//TypedValue[] values = new TypedValue[]
//{
// new TypedValue((int)DxfCode.Start,“circle”)
//};
//SelectionFilter filter = new SelectionFilter(values);
//PromptSelectionResult res = ed.SelectAll(filter);
//if (res.Status != PromptStatus.OK) return;

//ObjectId[] ids = res.Value.GetObjectIds();
//if (ids.Length == 0) return;
//CircleData[] datas = this.GetCircelData(db, ids);
保存数据到Excel文件
//this.SaveDataToExcel(fileName, datas);
#endregion

#region 读取Excel文件画图

string fileName = this.OpenFileDialog(ed, db);
if (fileName == “”) return;

List datas = this.GetDataFromExcel(fileName);
if (datas.Count == 0) return;

        this.DrawCircle(db, datas);
        #endregion
    }
    /// <summary>
    /// 将图形绘制到模型空间
    /// </summary>
    /// <param name="db"></param>
    /// <param name="datas"></param>
    private void DrawCircle(Database db, List<CircleData> datas)
    {
        using (Transaction trasns = db.TransactionManager.StartTransaction())
        {
            BlockTable bt = (BlockTable)trasns.GetObject(db.BlockTableId, OpenMode.ForRead);
            BlockTableRecord btr = (BlockTableRecord)trasns.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
            for (int i = 0; i < datas.Count; i++)
            {
                
                Point3d center = new Point3d(datas[i].X, datas[i].Y, datas[i].Z);
                double radius = datas[i].R;
                Circle c = new Circle(center,Vector3d.ZAxis,radius);
                btr.AppendEntity(c);
                trasns.AddNewlyCreatedDBObject(c, true);
            }
            trasns.Commit();
        }
    }

    /// <summary>
    /// 读取Excel数据
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    private List<CircleData> GetDataFromExcel(string fileName)
    {
        List<CircleData> datas = new List<CircleData>();
        Excel.Application excelApp = new Excel.Application(); //生命Excel程序
        Excel.Workbook book = excelApp.Workbooks.Open(fileName); //Excel工作簿
        Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets[1]; //获取第一张工作表
        int i = 2;
        while (sheet.Cells[i, 2].Value != null && sheet.Cells[i, 2].Value.ToString().Trim() != "")
        {
            CircleData data = new CircleData();
            data.R = (double)sheet.Cells[i, 2].Value;
            data.X = (double)sheet.Cells[i, 3].Value;
            data.Y = (double)sheet.Cells[i, 4].Value;
            data.Z = (double)sheet.Cells[i, 5].Value;
            datas.Add(data);
            i++;
        }
        excelApp.Quit(); //推出并销毁Excel程序
        excelApp.Dispose();
        return datas;
    }

    /// <summary>
    /// 保存数据到Excel文件
    /// </summary>
    /// <param name="fileName"></param>
    /// <param name="datas"></param>
    private void SaveDataToExcel(string fileName, CircleData[] datas)
    {
        Excel.Application excelApp = new Excel.Application(); //生命Excel程序
        Excel.Workbook book = excelApp.Workbooks.Add(); //Excel工作簿
        Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets[1]; //获取第一张工作表
        sheet.Cells[1, 1].Value = "序号";
        sheet.Cells[1, 2].Value = "半径";
        sheet.Cells[1, 3].Value = "X坐标";
        sheet.Cells[1, 4].Value = "Y坐标";
        sheet.Cells[1, 5].Value = "Z坐标";
        for (int i = 0; i < datas.Length; i++)
        {
            sheet.Cells[i + 2, 1].Value = i+1;
            sheet.Cells[i + 2, 2].Value = datas[i].R;
            sheet.Cells[i + 2, 3].Value = datas[i].X;
            sheet.Cells[i + 2, 4].Value = datas[i].Y;
            sheet.Cells[i + 2, 5].Value = datas[i].Z;
        }
        book.SaveAs(fileName); //保存工作簿
        excelApp.Quit(); //推出并销毁Excel程序
        excelApp.Dispose();
    }
    /// <summary>
    /// 获取图形对象的数据
    /// </summary>
    /// <param name="db"></param>
    /// <param name="ids"></param>
    /// <returns></returns>
    private CircleData[] GetCircelData(Database db, ObjectId[] ids)
    {
        CircleData[] datas = new CircleData[ids.Length];
        using (Transaction trans = db.TransactionManager.StartTransaction())
        {
            for (int i = 0; i < ids.Length; i++)
            {
                Circle c = (Circle)ids[i].GetObject(OpenMode.ForRead);
                datas[i].X = c.Center.X;
                datas[i].Y = c.Center.Y;
                datas[i].Z = c.Center.Z;
                datas[i].R = c.Radius;
            }
        }
        return datas;
    }
    /// <summary>
    /// 获取文件保存路径和文件名
    /// </summary>
    /// <param name="ed"></param>
    /// <param name="db"></param>
    /// <returns>文件全路径</returns>
    private string OpenSaveDialog(Editor ed,Database db)
    {
        
        string directoryName = Path.GetDirectoryName(db.Filename);
        string fileName = Path.GetFileName(db.Filename);
        fileName = fileName.Substring(0, fileName.IndexOf('.'));
        PromptSaveFileOptions opt = new PromptSaveFileOptions("保存Excel文件");
        opt.DialogCaption = "保存Excel文件";
        opt.Filter = "Excel 97-2003 工作簿(*.xls)|*.xls|Excel 工作簿(*.xlsx)|*.xlsx";
        opt.FilterIndex = 1;
        opt.InitialDirectory = directoryName;
        opt.InitialFileName = fileName;
        PromptFileNameResult fileRes = ed.GetFileNameForSave(opt);
        if (fileRes.Status == PromptStatus.OK)
        {
            fileName = fileRes.StringResult;
        }
        else
        {
            fileName = "";
        }
        return fileName;
    }
    /// <summary>
    /// 获取打开文件的全路径
    /// </summary>
    /// <param name="ed"></param>
    /// <param name="db"></param>
    /// <returns></returns>
    private string OpenFileDialog(Editor ed, Database db)
    {

        string directoryName = Path.GetDirectoryName(db.Filename);
        string fileName = Path.GetFileName(db.Filename);
        fileName = fileName.Substring(0, fileName.IndexOf('.'));
        PromptOpenFileOptions opt = new PromptOpenFileOptions("读取Excel文件");
        opt.DialogCaption = "读取Excel文件";
        opt.Filter = "Excel 工作簿(*.xlsx)|*.xlsx|Excel 97-2003 工作簿(*.xls)|*.xls";
        opt.FilterIndex = 0;
        opt.InitialDirectory = directoryName;
        opt.InitialFileName = fileName;
        PromptFileNameResult fileRes = ed.GetFileNameForOpen(opt);
        if (fileRes.Status == PromptStatus.OK)
        {
            fileName = fileRes.StringResult;
        }
        else
        {
            fileName = "";
        }
        return fileName;
    }
}

}


http://lihuaxi.xjx100.cn/news/1178914.html

相关文章

你在项目中是如何使用kafka的?

消息中间件是现代分布式系统中不可或缺的组件之一&#xff0c;它提供了高可靠性、高吞吐量的消息传递机制。Kafka作为一种开源的分布式消息队列系统&#xff0c;广泛应用于各行各业。本篇博客将介绍在实践中使用Kafka的一些技巧和最佳实践&#xff0c;帮助开发人员更好地利用Ka…

如何在华为OD机试中获得满分?Java实现【表示数字】一文详解!

✅创作者&#xff1a;陈书予 &#x1f389;个人主页&#xff1a;陈书予的个人主页 &#x1f341;陈书予的个人社区&#xff0c;欢迎你的加入: 陈书予的社区 &#x1f31f;专栏地址: Java华为OD机试真题&#xff08;2022&2023) 文章目录 1. 题目描述2. 输入描述3. 输出描述…

[元带你学: eMMC协议详解 10] Device 识别流程 与 中断模式

依JEDEC eMMC 5.1及经验辛苦整理&#xff0c;付费内容&#xff0c;禁止转载。 所在专栏 《元带你学: eMMC协议详解》 全文2700字&#xff0c;重点需掌握设备识别过程&#xff08;CMD1 -> CMD2 -> CMD3&#xff09;, 这很常用&#xff0c; 也是最容易出现异常的地方。其他…

Linux(基础IO详解)

在基础IO这篇博客中&#xff0c;我们将了解到文件系统的构成&#xff0c;以及缓冲区究竟是个什么东东&#xff0c;我们都知道缓冲区&#xff0c;有时也谈论缓冲区&#xff0c;但不一定真的去深入了解过缓冲区。为什么内存和磁盘交互速度如此之慢&#xff1f;为什么都说Linux中一…

【LeetCode热题100】打开第6天:正则表达式匹配

文章目录 正则表达式匹配⛅前言&#x1f512;题目&#x1f511;题解 正则表达式匹配 ⛅前言 大家好&#xff0c;我是知识汲取者&#xff0c;欢迎来到我的LeetCode热题100刷题专栏&#xff01; 精选 100 道力扣&#xff08;LeetCode&#xff09;上最热门的题目&#xff0c;适合…

【刷题之路】LeetCode 2073. 买票需要的时间

【刷题之路】LeetCode 2073. 买票需要的时间 一、题目描述二、解题1、方法1——记录每个人需要的时间1.1、思路分析1.2、代码实现 2、方法2——队列记录下标2.1、思路分析2.2、先将队列实现一下2.3、代码实现 一、题目描述 原题连接&#xff1a; 2073. 买票需要的时间 题目描述…

序列化_原理与应用

关键字&#xff1a;序列化,java,proto,json,字节序列,字节数组,byte array,serialize序列化简介 序列化 (Serialization)是将对象的状态信息转换为可以存储或传输的形式的过程。 如在内存中的java对象&#xff08;本是方便JVM使用的格式&#xff09;序列化为硬盘或是网络传输…

关于linux系统can收发,以及jetson系列can收发的说明,以及SN65HVD230 CAN board和MCP2515和TJA1050的区别是什么?

1&#xff0c;jetson orin、Tx2有can处理器&#xff0c;没有收发器 所以官方推荐用SN65HVD230 CAN board就可以了。理论上单独的TJA1050也是可以的。。。 2&#xff0c;如果本身没有can像jetson nano、香橙派这样&#xff0c;就需要使用MCP2515和TJA1050的结合体了 SN65HVD230…