using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Excel = NetOffice.ExcelApi;
using System;
using System.Collections.Generic;
using DotNetARX;
namespace NTTC
{
public class ExcelCAD
{
[CommandMethod("ExcelToCAD")]
public void ExcelToCAD()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
LateBindingApi.Core.Factory.Initialize();//初始化對COM物件的支持
Excel.Application excelapp = new Excel.Application();//申明一個Excel物件
PromptOpenFileOptions opt = new PromptOpenFileOptions("請選擇Excel檔案");//定義打開檔案對話框選項
opt.DialogCaption = "選擇Excel檔案";//檔案對話框的標題
//檔案對話框的檔案過濾器串列,可以是各個版本的Excel
opt.Filter = "Excel 97-2010作業簿(*.xls)|*.xls|Excel作業簿(*.xlsx)|*.xlsx";
opt.FilterIndex = 0;// 檔案過濾器串列中默認顯示的檔案擴展名
//根據用戶的選擇,獲取檔案名
PromptFileNameResult fileResult = ed.GetFileNameForOpen(opt);
if (fileResult.Status != PromptStatus.OK) return;
string filename = fileResult.StringResult;//設定檔案名變數
using (Transaction trans = db.TransactionManager.StartTransaction())
{//打開指定的Excel檔案,獲得指定頁的Sheet1
Excel.Workbook book = excelapp.Workbooks.Open(filename);
Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets["Sheet1"];
List<DBText> txts = new List<DBText>();//用于保存點的名稱的串列
List<DBPoint> points = new List<DBPoint>();//用于保存點的位置的串列
Application.SetSystemVariable("PDMODE", 35);//設定點的形狀
Application.SetSystemVariable("PDSIZE", 2);//設定點的大小
int i = 1;
//對單元格進行回圈,若為慷訓者空格則結束回圈
while (sheet.Cells[i + 1, 1].Value != null && sheet.Cells[i + 1, 1].Value.ToString().Trim() != "")
{
DBPoint pt = new DBPoint();//臨時變數用于儲存點的位置
DBText txt = new DBText();//臨時變數用于儲存點的名稱
//獲取點的名稱,位于第一列
txt.TextString = sheet.Cells[i + 1, i].Value.ToString();
//獲取點的x,y,z值分別位于第2、3、4列
double x = Convert.ToDouble(sheet.Cells[i + 1, 2].Value);
double y = Convert.ToDouble(sheet.Cells[i + 1, 3].Value);
double z = Convert.ToDouble(sheet.Cells[i + 1, 4].Value);
pt.Position = new Point3d(x, y, z);//設定點的位置
//設定文本的位置,位于點的右側
txt.Position = pt.Position.Add(new Vector3d(3, 0, 0));
points.Add(pt);//添加點的位置到對應的串列
txts.Add(txt);//添加點的名稱到對應的串列
i++;
}
db.AddToModelSpace(txts.ToArray());//添加點的名稱到當前模型空間
db.AddToModelSpace(points.ToArray());//添加點的位置到當前模型空間
trans.Commit();
}
excelapp.Quit();
excelapp.Dispose();
}
}
}
提示錯誤

cad是2010版,.net4.0版本
uj5u.com熱心網友回復:
錯了,,cad2012版本,,.net4.0轉載請註明出處,本文鏈接:https://www.uj5u.com/net/81416.html
標籤:C#
