/// <summary> /// 从database读取直线的数据,并将数据保存到excel表 /// </summary> [CommandMethod('ToExcel')] public void ToExcel() { Database db = HostApplicationServices.WorkingDatabase; System.Data.DataTable table = new System.Data.DataTable(); table.TableName = '直线表'; table.Columns.Add('操作', typeof(string)); table.Columns.Add('起点坐标X',typeof(double )); table.Columns.Add('起点坐标Y', typeof(double)); table.Columns.Add('起点坐标Z', typeof(double)); table.Columns.Add('终点坐标X', typeof(double)); table.Columns.Add('终点坐标Y', typeof(double)); table.Columns.Add('终点坐标Z', typeof(double)); 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; foreach (ObjectId objectId in btr) { Line line = tr.GetObject(objectId,OpenMode.ForRead) as Line; System.Data.DataRow row = table.NewRow(); if (line!=null) { row[0] = line.Handle.ToString(); row[1] = line.StartPoint.X; row[2] = line.StartPoint.Y; row[3] = line.StartPoint.Z; row[4] = line.EndPoint.X; row[5] = line.EndPoint.Y; row[6] = line.EndPoint.Z; } table.Rows.Add(row); } tr.Commit(); } SaveTo(table, @'C:\Users\Administrator\Desktop\LineData.xlsx'); } /// <summary> /// 将数据保存到excel表格 /// </summary> /// <param name='table'></param> /// <param name='fileName'></param> private void SaveTo(System.Data.DataTable table, string fileName) { int columnIndex = 1; int rowIndex = 1; Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); excelApp.DefaultFilePath = fileName; excelApp.DisplayAlerts = true; excelApp.SheetsInNewWorkbook = 1; Microsoft.Office.Interop.Excel.Workbook workbook = excelApp.Workbooks.Add(true); foreach (System.Data.DataColumn column in table.Columns) { excelApp.Cells[rowIndex, columnIndex] = column.ColumnName; columnIndex++; } for (int i = 0; i < table.Rows.Count; i++) { columnIndex = 1; rowIndex++; for (int j = 0; j < table.Columns.Count; j++) { excelApp.Cells[rowIndex, columnIndex] = table.Rows[i][j].ToString(); columnIndex++; } } workbook.SaveCopyAs(fileName); excelApp = null; workbook = null; } |
|