NPOI是一个免费且开源的.NET库,用于操作Excel文件[^0^]。它支持读取、修改和生成Excel文件,兼容 .xls (Excel 97-2003格式)和 .xlsx (Excel 2007及以上版本的OpenXML格式)
0、采用interope
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
using OpenFileDialog = System.Windows.Forms.OpenFileDialog;
[assembly: CommandClass(typeof(IFoxDemo.ExcelToPolylineCommand))]//只允许此类快捷键命令
namespace IFoxDemo
{
public class ExcelToPolylineCommand
{
[CommandMethod("xx")]
public void ExcelToPolyline()
{
Document doc = Acap.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
// 弹窗提示用户选择 Excel 文件
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel Files|*.xls;*.xlsx";
openFileDialog.Title = "选择包含坐标的 Excel 文件";
if (openFileDialog.ShowDialog() != DialogResult.OK)
{
ed.WriteMessage("\n用户取消操作。");
return;
}
string filePath = openFileDialog.FileName;
// 创建Excel应用程序对象
Excel.Application excelApp = new Excel.Application();
//excelApp.Visible =true;
try
{
// 读取 Excel 文件
Workbook workbook = excelApp.Workbooks.Open(filePath);
//Excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\Users\Administrator\Desktop\2.xls");
Excel.Worksheet worksheet =(Excel.Worksheet)workbook.Sheets[1]; // 获取第一个工作表
Excel.Range range = worksheet.UsedRange;
// 存储坐标点
List<Point2d> points = new List<Point2d>();
// 遍历工作表的行
for (int i = 1; i < range.Rows.Count; i++)
{
// 读取点号、X、Y 坐标
//string pointNumber = range.Cells[i, 1].ToString(); // 点号
double x = Convert.ToDouble((range.Cells[i, 1] as Excel.Range).Value2);// 坐标
double y = Convert.ToDouble((range.Cells[i, 2] as Excel.Range).Value2); // Y坐标
// 将坐标添加到点集合
points.Add(new Point2d(x, y));
ed.WriteMessage($"\n读取点 : X = {x}, Y = {y}");
//ed.WriteMessage($"\n读取点 {pointNumber}: X = {x}, Y = {y}");
}
关闭excel释放对象(excelApp, workbook, worksheet);
if (points.Count < 2)
{
ed.WriteMessage("\n至少需要两个点来创建多段线。");
return;
}
// 创建多段线
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
Polyline polyline = new Polyline();
polyline.Color = ColorName.hong;
for (int i = 0; i < points.Count; i++)
{
polyline.AddVertexAt(i, points[i], 0, 0, 0);
}
// 闭合多段线(可选)
polyline.Closed = true;
btr.AppendEntity(polyline);
tr.AddNewlyCreatedDBObject(polyline, true);
tr.Commit();
}
ed.WriteMessage($"\n成功创建多段线,包含 {points.Count} 个点。");
}
catch (Exception ex)
{
ed.WriteMessage($"\n错误: {ex.Message}");
}
// 退出Excel应用程序
// 关闭Excel工作簿和应用程序
}
private static void 关闭excel释放对象(Excel.Application excelApp, Workbook workbook, Worksheet worksheet)
{
// 关闭Excel工作簿和应用程序
workbook.Close(false);
excelApp.Quit();
// 释放COM对象
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(excelApp);
}
}
}
一、采用Aspose包
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Aspose.Cells;
using OpenFileDialog = System.Windows.Forms.OpenFileDialog;
[assembly: CommandClass(typeof(IFoxDemo.ExcelToPolylineCommand))]//只允许此类快捷键命令
namespace IFoxDemo
{
public class 配电箱线路连接
{
[CommandMethod("aaa")]
public void demo()
{
"XXOK".Print();
}
}
public class ExcelToPolylineCommand
{
[CommandMethod("xx")]
public void ExcelToPolyline()
{
Document doc = Acap.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
// 弹窗提示用户选择 Excel 文件
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel Files|*.xls;*.xlsx";
openFileDialog.Title = "选择包含坐标的 Excel 文件";
if (openFileDialog.ShowDialog() != DialogResult.OK)
{
ed.WriteMessage("\n用户取消操作。");
return;
}
string filePath = openFileDialog.FileName;
try
{
// 读取 Excel 文件
Workbook workbook = new Workbook(filePath);
Worksheet worksheet = workbook.Worksheets[0]; // 获取第一个工作表
// 存储坐标点
List<Point2d> points = new List<Point2d>();
// 遍历工作表的行
for (int row = 1; row < worksheet.Cells.MaxDataRow + 1; row++)
{
// 读取点号、X、Y 坐标
string pointNumber = worksheet.Cells[row, 0].StringValue; // 点号
double x = worksheet.Cells[row, 1].DoubleValue; // X 坐标
double y = worksheet.Cells[row, 2].DoubleValue; // Y 坐标
// 将坐标添加到点集合
points.Add(new Point2d(x, y));
ed.WriteMessage($"\n读取点 {pointNumber}: X = {x}, Y = {y}");
}
if (points.Count < 2)
{
ed.WriteMessage("\n至少需要两个点来创建多段线。");
return;
}
// 创建多段线
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
Polyline polyline = new Polyline();
for (int i = 0; i < points.Count; i++)
{
polyline.AddVertexAt(i, points[i], 0, 0, 0);
}
// 闭合多段线(可选)
polyline.Closed = true;
btr.AppendEntity(polyline);
tr.AddNewlyCreatedDBObject(polyline, true);
tr.Commit();
}
ed.WriteMessage($"\n成功创建多段线,包含 {points.Count} 个点。");
}
catch (Exception ex)
{
ed.WriteMessage($"\n错误: {ex.Message}");
}
Env.Editor.ZoomExtents();
}
}
}
二、后期绑定无提示:
namespace WindowsFormsApp2
{
internal static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void 获取当前excel_Click(object sender, EventArgs e)
{
try
{
//后期绑定获取当前excel
dynamic Excelapp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");//object换成动态dynamic
Excelapp.visible = true;
dynamic wbk = Excelapp.Workbooks.Add();
dynamic wst = wbk.Worksheets[1];//com中数组第一个item是1
wst.Name = "dz";
string[] title = new string[] { "姓名", "年龄", "住所" };
wst.Range["A1:C1"].Value = title;
}
catch (Exception)
{
MessageBox.Show(" 错了");
}
}
private void 关闭当前excel_Click(object sender, EventArgs e)
{
dynamic Excelapp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");//object换成动态dynamic
//Excelapp.DisplayAlerts = false;
Excelapp.Quit();
Excelapp.Quit();
}
private void 打开excel_Click(object sender, EventArgs e)
{
System.Type ET = System.Type.GetTypeFromProgID("Excel.Application");
dynamic Excelapp = System.Activator.CreateInstance(ET);
Excelapp.visible = true;
dynamic wbk = Excelapp.Workbooks.Add();
dynamic wst = wbk.Worksheets[1];//com中数组第一个item是1
wst.Name = "dz";
string[] title = new string[] { "姓名", "年龄", "住所" };
wst.Range["A1:C1"].Value = title;
}
private void 关闭窗口_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
三、前期绑定有提示方法:程序集—>扩展
g:\Program Files (x86)\Microsoft Visual Studio\Shared\Visual Studio Tools for Office\PIA\Office15\Microsoft.Office.Interop.Excel.dll
using AcTools;
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;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void 获取当前excel_Click(object sender, EventArgs e)
{
try
{
//后期绑定获取当前excel
dynamic Excelapp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");//object换成动态dynamic
Excelapp.visible = true;
dynamic wbk = Excelapp.Workbooks.Add();
dynamic wst = wbk.Worksheets[1];//com中数组第一个item是1
wst.Name = "dz";
string[] title = new string[] { "姓名", "年龄", "住所" };
wst.Range["A1:C1"].Value = title;
}
catch (Exception)
{
MessageBox.Show(" 错了");
}
}
private void 关闭当前excel_Click(object sender, EventArgs e)
{
int i = 0;
while (i<10)
{
dynamic Excelapp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");//object换成动态dynamic
//Excelapp.DisplayAlerts = false;
Excelapp.Quit();
Excelapp.Quit();
i++;
}
}
private void 打开excel_Click(object sender, EventArgs e)
{
System.Type ET = System.Type.GetTypeFromProgID("Excel.Application");
dynamic Excelapp = System.Activator.CreateInstance(ET);
Excelapp.visible = true;
dynamic wbk = Excelapp.Workbooks.Add();
dynamic wst = wbk.Worksheets[1];//com中数组第一个item是1
wst.Name = "dz";
string[] title = new string[] { "姓名", "年龄", "住所" };
wst.Range["A1:C1"].Value = title;
Excelapp.WindowState = -4143;
}
private void 关闭窗口_Click(object sender, EventArgs e)
{
this.Close();
}
private void 前期绑定excel_Click(object sender, EventArgs e)
{
var excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
var wb = excel.Workbooks.Add();//var 替代Microsoft.Office.Interop.Excel.Workbook
Microsoft.Office.Interop.Excel.Worksheet ws = wb.Worksheets[1];//var 替代Microsoft.Office.Interop.Excel.Worksheet
ws.Name = "前期绑定";
ws.Cells[3,5].Value = "HELLO";
excel.DisplayAlerts = true;
excel.Quit();
}
private void button1_Click(object sender, EventArgs e)
{
// dynamic cad = System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCad.Application");//无提示
AutoCAD.AcadApplication cad = System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCad.Application") as AutoCAD.AcadApplication;
cad.Visible = true;
var doc = cad.Documents.Add();
System.Double[]c = new double[3] { 0,0,0};
System.Double r = 100;
var y = doc.ModelSpace.AddCircle(c,r);
cad.ZoomAll();
cad.Quit();
}
}
}
cad前期绑定可兼容早期cad2007版本,后期绑定不适用2007;
C#运行vba已存在的宏