学习使用C#来开发AutoCAD已经近两周。
由于开发的是工程小插件,免不了经常需要在Cad和Excel的数据间进行切换。
这里贴出一段代码,示例如何从Excel按Ctrl+C后(剪贴板)生成一个二维数组。
但这段代码希望高手能够提供改进意见,因为有如下问题仍未处理:
1)未判断数据类型是否来自于Excel
2)未判断剪贴板上是否有数据
-
- public static double[][] GetDataFromExcel()
- {
- if (System.Windows.Forms.Clipboard.GetDataObject() != null) // 确保粘贴板中有内容
- {
- Document dc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
- Editor ed = dc.Editor;
- IDataObject io = System.Windows.Forms.Clipboard.GetDataObject();
- string strSum = (string)io.GetData(DataFormats.Text);
- string[] strRows = strSum.Split('\n');
- int rowNum = strRows.Length-1; // 获得行数
- string[] strCols = strRows[1].Split('\t');
- int colNum = strCols.Length;
- double[][] res = new double[rowNum][];
- for (int i = 0; i < rowNum; i++)
- {
- res = new double[colNum];
- string[] newCol = strRows.Split('\t');
- for (int j = 0; j < colNum; j++)
- {
- try
- {
- res[j] = double.Parse(newCol[j]);
- }
- catch (System.Exception err)
- {
- ed.WriteMessage("\n 数据有误" + err.Message);
- }
- finally
- {
- ed.WriteMessage("\n" + res[j].ToString());
- }
- }
- }
- return res;
- // 以下为测试代码
- //Document rxDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
- //Editor ed = rxDoc.Editor;
- //for (int i = 0; i < rowNum; i++)
- //{
- // ed.WriteMessage("\n");
- // for (int j = 0; j < colNum; j++)
- // {
- // ed.WriteMessage(res[j].ToString() + "\t");
- // }
- //}
- ////return res;
- //ed.WriteMessage("\n 共" + rowNum.ToString()+"行");
- //ed.WriteMessage("\n 共" + colNum.ToString() + "列");
- }
- else
- {
- Document rxDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
- Editor ed = rxDoc.Editor;
- ed.WriteMessage("\n检测到未从Excel中复制内容,请重试。");
- double[][] res = new double[1][];
- return res;
- }
- }
注意包含以下API空间引用:
-
- using System.Data;
- using System.IO;
- using System.Windows.Forms;
- using System.Web;
- using System.Reflection;
- using excel = Microsoft.Office.Interop.Excel;
- using System.ComponentModel;
- using System.Runtime.Serialization.Formatters.Binary;
可取消注释掉的代码在命令行内看执行结果。
|