異世界


2014年7月12日 星期六

使用List<T>做為資料實體,XML 或 bin file 作為資料檔案

 

不使用資料庫一樣能完成資料存取,並使用 dataGridView、bindingNavigator 來瀏覽資料。

使用 List<T> 做為資料實體,XML 或 bin file 作為資料檔案。

1. 建立List<T>擴充方法

2. 使用 NPOI 實現Excel 檔案操作 (c# NPOI 教程(目錄),存取 Excel 檔案的利器:NPOI Library )

3. 2014/12/25 加註=> NPOI 已經可以產生  xlsx : http://www.dotblogs.com.tw/mis2000lab/archive/2014/07/02/npoi-20-for-aspnet_20140703.aspx

以下程式碼來自網路並經修改

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5: using System.Data;
   6: using System.Reflection;
   7: using System.Windows.Forms;
   8: using System.IO;
   9: using System.Runtime.Serialization.Formatters.Binary;
  10: using System.Xml;
  11: using System.Xml.Serialization;
  12: using System.Resources;
  13:  
  14: using NPOI;
  15: using NPOI.HPSF;
  16: using NPOI.HSSF;
  17: using NPOI.HSSF.UserModel;
  18: using NPOI.POIFS;
  19: using NPOI.POIFS.FileSystem;
  20: using NPOI.SS.UserModel;
  21: using NPOI.Util;
  22: using System.ComponentModel;
  23:  
  24:  
  25: namespace Laser5Axis.Extension
  26: {
  27:     /// <summary>
  28:     /// 原資訊來自:http://www.dotblogs.com.tw/gelis/archive/2012/04/15/71535.aspx
  29:     /// 已經部分增刪修改
  30:     /// </summary>
  31:     /// 
  32:     /// 擴充方法必須定義為靜態方法,但使用執行個體方法語法進行呼叫。 
  33:     /// 擴充方法的第一個參數指定方法進行作業的型別,而這個參數的前面需加上 this 修飾詞 (Modifier)。 
  34:     /// 使用 using 指示詞,將命名空間 (Namespace) 明確匯入至原始程式碼時,擴充方法才會進入範圍中。 
  35:     /// 
  36:     public static class ListExtensionMethod
  37:     {
  38:         public static void getComboBoxColumn<T>(this List<T> list, string key, string name, ref DataGridViewComboBoxColumn ComboBoxColumn)
  39:         {
  40:             if (list.Count <= 0) { return; }
  41:  
  42:             //DataGridViewComboBoxColumn ComboBoxColumn = new DataGridViewComboBoxColumn();
  43:             {
  44:                 ComboBoxColumn.DataPropertyName = name;
  45:                 ComboBoxColumn.HeaderText = name;
  46:                 ComboBoxColumn.DropDownWidth = 160;
  47:                 ComboBoxColumn.Width = 90;
  48:                 ComboBoxColumn.MaxDropDownItems = 5;
  49:                 ComboBoxColumn.FlatStyle = FlatStyle.Flat;
  50:  
  51:                 foreach (var p in list)
  52:                 {
  53:                     PropertyInfo[] pPty = p.GetType().GetProperties();
  54:  
  55:                     foreach (PropertyInfo pp in pPty)
  56:                     {
  57:                         if (pp.MemberType == MemberTypes.Property)
  58:                         {
  59:                             if (pp.Name == key)
  60:                             {
  61:                                 ComboBoxColumn.Items.Add(pp.GetValue(p, null));
  62:                             }
  63:                         }
  64:                     }
  65:                 }
  66:             }
  67:  
  68:             //return ComboBoxColumn;
  69:         }
  70:         //public static DataTable getTable<T>(this List<T> list, ref DataTable subTable)
  71:         //{
  72:         //    DataTable dt = new DataTable();
  73:         //    if (list.Count > 0)
  74:         //    {
  75:         //        Type obj = list.Take(1).Single().GetType();     //若有資料,
  76:         //        PropertyInfo[] pInfo = obj.GetProperties();
  77:         //        dt.TableName = obj.Name;
  78:  
  79:         //        foreach (PropertyInfo info in pInfo)
  80:         //        {
  81:         //            if (info.MemberType == MemberTypes.Property)
  82:         //            {
  83:         //                //.. List<BitMapping>
  84:         //                if (info.PropertyType == typeof(List<nmsBit>)) { }
  85:         //                dt.Columns.Add(new DataColumn(info.Name));
  86:         //            }
  87:         //        }
  88:         //    }
  89:  
  90:         //    foreach (var p in list)
  91:         //    {
  92:         //        PropertyInfo[] pPty = p.GetType().GetProperties();
  93:  
  94:         //        DataRow dr = dt.NewRow();
  95:  
  96:         //        foreach (PropertyInfo pp in pPty)
  97:         //        {
  98:         //            if (pp.MemberType == MemberTypes.Property)
  99:         //            {
 100:         //                //if (pp.Name == "Mappings") { }
 101:         //                dr[pp.Name] = pp.GetValue(p, null);
 102:         //            }
 103:         //        }
 104:         //        dt.Rows.Add(dr);
 105:         //    }
 106:  
 107:         //    return dt;
 108:         //}
 109:         public static DataTable getTable<T>(this List<T> list)
 110:         {
 111:             DataTable dt = new DataTable();
 112:             if (list.Count > 0)
 113:             {
 114:                 Type obj = list.Take(1).Single().GetType();     //若有資料,
 115:                 PropertyInfo[] pInfo = obj.GetProperties();
 116:                 dt.TableName = obj.Name;
 117:  
 118:                 foreach (PropertyInfo info in pInfo)
 119:                 {
 120:                     if (info.MemberType == MemberTypes.Property)
 121:                     {
 122:                         dt.Columns.Add(new DataColumn(info.Name));
 123:                     }
 124:                 }
 125:             }
 126:  
 127:             foreach (var p in list)
 128:             {
 129:                 PropertyInfo[] pPty = p.GetType().GetProperties();
 130:  
 131:                 DataRow dr = dt.NewRow();
 132:  
 133:                 foreach (PropertyInfo pp in pPty)
 134:                 {
 135:                     if (pp.MemberType == MemberTypes.Property)
 136:                     {
 137:                         dr[pp.Name] = pp.GetValue(p, null);
 138:                     }
 139:                 }
 140:                 dt.Rows.Add(dr);
 141:             }
 142:  
 143:             return dt;
 144:         }
 145:         public static DataTable ListToDataTable<T>(this IEnumerable<T> list) where T : class, new()
 146:         {
 147:             //建立一個回傳用的 DataTable
 148:             DataTable dt = new DataTable();
 149:  
 150:             //取得映射型別
 151:             Type type = typeof(T);
 152:  
 153:             //宣告一個 PropertyInfo 陣列,來接取 Type 所有的共用屬性
 154:             PropertyInfo[] PI_List = null;
 155:  
 156:             foreach (var item in list)
 157:             {
 158:                 //判斷 DataTable 是否已經定義欄位名稱與型態
 159:                 if (dt.Columns.Count == 0)
 160:                 {
 161:                     //取得 Type 所有的共用屬性
 162:                     PI_List = item.GetType().GetProperties();
 163:  
 164:                     //將 List 中的 名稱 與 型別,定義 DataTable 中的欄位 名稱 與 型別
 165:                     foreach (var item1 in PI_List)
 166:                     {
 167:                         dt.Columns.Add(item1.Name, item1.PropertyType);
 168:                     }
 169:                 }
 170:  
 171:                 //在 DataTable 中建立一個新的列
 172:                 DataRow dr = dt.NewRow();
 173:  
 174:                 //將資料逐筆新增到 DataTable 中
 175:                 foreach (var item2 in PI_List)
 176:                 {
 177:                     dr[item2.Name] = item2.GetValue(item, null);
 178:                 }
 179:  
 180:                 dt.Rows.Add(dr);
 181:             }
 182:  
 183:             dt.AcceptChanges();
 184:  
 185:             return dt;
 186:         }
 187:         public static List<T> DataTableToList<T>(this DataTable dt) where T : class, new()
 188:         {
 189:             //建立一個回傳用的 List<TResult>
 190:             List<T> list = new List<T>();
 191:  
 192:             //取得映射型別
 193:             Type type = typeof(T);
 194:  
 195:             //儲存 DataTable 的欄位名稱
 196:             List<PropertyInfo> pr_List = new List<PropertyInfo>();
 197:  
 198:             foreach (PropertyInfo item in type.GetProperties())
 199:             {
 200:                 if (dt.Columns.IndexOf(item.Name) != -1)
 201:                     pr_List.Add(item);
 202:             }
 203:  
 204:             //逐筆將 DataTable 的值新增到 List<T> 中
 205:             foreach (DataRow item in dt.Rows)
 206:             {
 207:                 T tr = new T();
 208:  
 209:                 foreach (PropertyInfo item1 in pr_List)
 210:                 {
 211:                     if (item[item1.Name] != DBNull.Value)
 212:                         item1.SetValue(tr, item[item1.Name], null);  //資料型態不同時 就拋出例外(如何轉型 ???)
 213:                 }
 214:  
 215:                 list.Add(tr);
 216:             }
 217:  
 218:             return list;
 219:         }
 220:  
 221:  
 222:         /// <summary>
 223:         /// 將 List<T> 轉換為 DataSet 並存為XML檔案.
 224:         /// </summary>
 225:         /// <typeparam name="T"></typeparam>
 226:         /// <param name="list"></param>
 227:         public static int SaveToDisk<T>(this List<T> list, string XmlPath)
 228:         {
 229:             int result = 0;
 230:             DataTable dt = new DataTable();
 231:             if (list.Count > 0)
 232:             {
 233:                 Type obj = list.Take(1).Single().GetType();     //若有資料,
 234:                 PropertyInfo[] pInfo = obj.GetProperties();
 235:                 dt.TableName = obj.Name;
 236:  
 237:                 foreach (PropertyInfo info in pInfo)
 238:                 {
 239:                     if (info.MemberType == MemberTypes.Property)
 240:                     {
 241:                         dt.Columns.Add(new DataColumn(info.Name));
 242:                     }
 243:                 }
 244:             }
 245:             else
 246:                 return result;
 247:  
 248:             foreach (var p in list)
 249:             {
 250:                 PropertyInfo[] pPty = p.GetType().GetProperties();
 251:  
 252:                 DataRow dr = dt.NewRow();
 253:  
 254:                 foreach (PropertyInfo pp in pPty)
 255:                 {
 256:                     if (pp.MemberType == MemberTypes.Property)
 257:                     {
 258:                         dr[pp.Name] = pp.GetValue(p, null);
 259:                     }
 260:                 }
 261:                 dt.Rows.Add(dr);
 262:                 result++;
 263:             }
 264:             dt.WriteXml(XmlPath);
 265:  
 266:             return result;
 267:         }
 268:         /// <summary>
 269:         /// 從磁碟讀取 DataSet 的 XML 檔案.
 270:         /// </summary>
 271:         /// <typeparam name="T"></typeparam>
 272:         /// <param name="list"></param>
 273:         public static List<T> LoadFromDisk<T>(this List<T> list, string XmlPath)
 274:         {
 275:             List<T> t = new List<T>();
 276:  
 277:             DataSet ds = new DataSet();
 278:             ds.ReadXml(XmlPath);
 279:             DataTable dt = ds.Tables["ATable"];
 280:             //dt.ReadXml(XmlPath);
 281:             foreach (DataRow dr in dt.Rows)
 282:             {
 283:                 T p = Activator.CreateInstance<T>();
 284:                 foreach (DataColumn col in dt.Columns)
 285:                 {
 286:                     Type pType = p.GetType();
 287:                     PropertyInfo pInfo = pType.GetProperty(col.ColumnName);
 288:                     if (pInfo.PropertyType == typeof(System.Int32))
 289:                     {
 290:                         pInfo.SetValue(p, Convert.ToInt32(dr[col.ColumnName]), null);
 291:                     }
 292:                     else
 293:                     {
 294:                         pInfo.SetValue(p, dr[col.ColumnName], null);
 295:                     }
 296:                 }
 297:                 t.Add(p);
 298:             }
 299:             return t;
 300:         }
 301:         /// <summary>
 302:         /// 將 List<T> Bin 序列化後存檔 
 303:         /// </summary>
 304:         /// <typeparam name="T"></typeparam>
 305:         /// <param name="list"></param>
 306:         /// <param name="XmlPath"></param>
 307:         /// <returns></returns>
 308:         public static int binSaveToDisk<T>(this List<T> list, string BinPath)
 309:         {
 310:             try
 311:             {
 312:                 using (Stream stream = File.Open(BinPath, FileMode.Create))
 313:                 {
 314:                     BinaryFormatter bin = new BinaryFormatter();
 315:                     bin.Serialize(stream, list);
 316:                     return list.Count;
 317:                 }
 318:             }
 319:             catch (IOException)
 320:             {
 321:                 return -1;
 322:             }
 323:         }
 324:         /// <summary>
 325:         /// 讀取序列化 Bin 檔案到 List<T>
 326:         /// </summary>
 327:         /// <typeparam name="T"></typeparam>
 328:         /// <param name="list"></param>
 329:         /// <param name="XmlPath"></param>
 330:         /// <returns></returns>
 331:         public static List<T> binLoadFromDisk<T>(this List<T> list, string BinPath)
 332:         {
 333:             try
 334:             {
 335:                 using (Stream stream = File.Open(BinPath, FileMode.Open))
 336:                 {
 337:                     BinaryFormatter bin = new BinaryFormatter();
 338:  
 339:                     list = (List<T>)bin.Deserialize(stream);
 340:                     return list;
 341:                 }
 342:             }
 343:             catch (IOException)
 344:             {
 345:                 return list;
 346:             }
 347:         }
 348:  
 349:  
 350:         #region < 還不能用 >
 351:         /// <summary>
 352:         /// 將 List<T> XML 序列化後存檔 
 353:         /// </summary>
 354:         /// <typeparam name="T"></typeparam>
 355:         /// <param name="list"></param>
 356:         /// <param name="BinPath"></param>
 357:         /// <returns></returns>+
 358:         public static int xmlSaveToDisk<T>(this List<T> list, string XmlPath)
 359:         {
 360:             System.Type t = typeof(List<T>);
 361:             XmlSerializer x = new XmlSerializer(t);
 362:             TextWriter writer = new StreamWriter(XmlPath);
 363:             x.Serialize(writer, list);
 364:             return list.Count;
 365:         }
 366:         /// <summary>
 367:         /// 讀取序列化 XML 檔案到 List<T>
 368:         /// </summary>
 369:         /// <typeparam name="T"></typeparam>
 370:         /// <param name="list"></param>
 371:         /// <param name="XmlPath"></param>
 372:         /// <returns></returns>
 373:         public static List<T> xmlLoadFromDisk<T>(this List<T> list, string XmlPath)
 374:         {
 375:             return list;
 376:         }
 377:         #endregion
 378:  
 379:         /* for Excel */
 380:         /// <summary>
 381:         /// ExportExcel : 用來匯出Excel檔案
 382:         /// GetDisplayName : 取得DisplayNameAttribute中所設定的名稱
 383:         /// GetPropertyDisplayNames : 取得Property的顯示名稱,用來當作標題
 384:         /// GetPropertyValues : 取得Property的值
 385:         /// <summary>
 386:         public static void ExportExcel<T>(this List<T> dataList, string fileName, string SheetName)
 387:         {
 388:             //int result = 0;
 389:             var datatype = typeof(T);
 390:  
 391:             //Create workbook
 392:             HSSFWorkbook hssfworkbook = new HSSFWorkbook();
 393:             ISheet sheet = hssfworkbook.CreateSheet(string.Format("{0}", datatype.GetDisplayName()));
 394:             hssfworkbook.SetSheetName(0, SheetName); // 修改 Sheet Name.
 395:  
 396:             //Insert titles
 397:             var row = sheet.CreateRow(0);
 398:             var titleList = datatype.GetPropertyDisplayNames();
 399:             for (int i = 0; i < titleList.Count; i++)
 400:             {
 401:                 row.CreateCell(i).SetCellValue(titleList[i]);
 402:             }
 403:  
 404:             //Insert data values
 405:             for (int i = 1; i < dataList.Count() + 1; i++)
 406:             {
 407:                 var tmpRow = sheet.CreateRow(i);
 408:                 var valueList = dataList.ElementAt(i - 1).GetPropertyValues();
 409:  
 410:                 for (int j = 0; j < valueList.Count; j++)
 411:                 {
 412:                     tmpRow.CreateCell(j).SetCellValue(valueList[j]);
 413:                 }
 414:             }
 415:  
 416:             //Save file
 417:             FileStream file = new FileStream(fileName, FileMode.Create);
 418:             hssfworkbook.Write(file);
 419:             file.Close();
 420:         }
 421:         public static string GetDisplayName(this MemberInfo memberInfo)
 422:         {
 423:             var titleName = string.Empty;
 424:  
 425:             //Try get DisplayName
 426:             var attribute = memberInfo.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault();
 427:             if (attribute != null)
 428:             {
 429:                 titleName = (attribute as DisplayNameAttribute).DisplayName;
 430:             }
 431:             //If no DisplayName
 432:             else
 433:             {
 434:                 titleName = memberInfo.Name;
 435:             }
 436:  
 437:             return titleName;
 438:         }
 439:         public static List<string> GetPropertyDisplayNames(this Type type)
 440:         {
 441:             var titleList = new List<string>();
 442:             var propertyInfos = type.GetProperties();
 443:  
 444:             foreach (var propertyInfo in propertyInfos)
 445:             {
 446:                 var titleName = propertyInfo.GetDisplayName();
 447:  
 448:                 titleList.Add(titleName);
 449:             }
 450:  
 451:             return titleList;
 452:         }
 453:         /// <summary>
 454:         /// 該方法已經將 List<T> 的所有數據均轉成 string 傳回。故存入Excel的都是 string
 455:         /// </summary>
 456:         public static List<string> GetPropertyValues<T>(this T data)
 457:         {
 458:             var propertyValues = new List<string>();
 459:             var propertyInfos = data.GetType().GetProperties();
 460:  
 461:             foreach (var propertyInfo in propertyInfos)
 462:             {
 463:                 propertyValues.Add(propertyInfo.GetValue(data, null).ToString());
 464:             }
 465:  
 466:             return propertyValues;
 467:         }
 468:         /// <summary>
 469:         /// 要將 Excel 轉到 List<T> 還有問題未解決。
 470:         /// Excel 載入的全是 string 除非我使用 List<string> 否則會出錯 ?????
 471:         /// </summary>
 472:         public static List<T> ImportExcel<T>(this List<T> list, string ExcelFileName, string SheetName) where T : class, new()
 473:         {
 474:             DataTable table = new DataTable();
 475:  
 476:             using (FileStream fs = new FileStream(ExcelFileName, FileMode.Open))
 477:             {
 478:                 //DataTable dt = RenderDataTableFromExcel(fs, 0, 0);
 479:                 table = jExcel.RenderDataTableFromExcel(fs, SheetName, 0);
 480:             }
 481:  
 482:             List<T> L = new List<T>();
 483:             L = DataTableToList<T>(table);
 484:             return list;
 485:         }
 486:     }
 487:  
 488:     public static class jExcel
 489:     {
 490:         public static Stream RenderDataTableToExcel(DataTable SourceTable)
 491:         {
 492:             HSSFWorkbook hssfworkbook = new HSSFWorkbook();
 493:             MemoryStream ms = new MemoryStream();
 494:             ISheet sheet = hssfworkbook.CreateSheet();
 495:             IRow headerRow = sheet.CreateRow(0);
 496:  
 497:             // handling header.
 498:             foreach (DataColumn column in SourceTable.Columns)
 499:                 headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
 500:  
 501:             // handling value.
 502:             int rowIndex = 1;
 503:  
 504:             foreach (DataRow row in SourceTable.Rows)
 505:             {
 506:                 IRow dataRow = sheet.CreateRow(rowIndex);
 507:  
 508:                 foreach (DataColumn column in SourceTable.Columns)
 509:                 {
 510:                     dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
 511:                 }
 512:  
 513:                 rowIndex++;
 514:             }
 515:  
 516:             hssfworkbook.Write(ms);
 517:             ms.Flush();
 518:             ms.Position = 0;
 519:  
 520:             sheet = null;
 521:             headerRow = null;
 522:             hssfworkbook = null;
 523:  
 524:             return ms;
 525:         }
 526:         public static void RenderDataTableToExcel(DataTable SourceTable, string FileName)
 527:         {
 528:             MemoryStream ms = RenderDataTableToExcel(SourceTable) as MemoryStream;
 529:             FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);
 530:             //FileStream fs = new FileStream(FileName, FileMode.Append, FileAccess.Write); //..在檔案存在時開啟它並搜尋至檔案末端,或建立新檔案
 531:  
 532:             byte[] data = ms.ToArray();
 533:  
 534:             fs.Write(data, 0, data.Length);
 535:             fs.Flush();
 536:             fs.Close();
 537:  
 538:             data = null;
 539:             ms = null;
 540:             fs = null;
 541:         }
 542:         public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, string SheetName, int HeaderRowIndex)
 543:         {
 544:             HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);
 545:             ISheet sheet = workbook.GetSheet(SheetName);
 546:             return RenderDataTableFromExcelMethod(ExcelFileStream, HeaderRowIndex, ref workbook, ref sheet);
 547:         }
 548:         public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex)
 549:         {
 550:             HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);
 551:             ISheet sheet = workbook.GetSheetAt(SheetIndex);
 552:             return RenderDataTableFromExcelMethod(ExcelFileStream, HeaderRowIndex, ref workbook, ref sheet);
 553:         }
 554:         private static DataTable RenderDataTableFromExcelMethod(Stream ExcelFileStream, int HeaderRowIndex, ref HSSFWorkbook workbook, ref ISheet sheet)
 555:         {
 556:             //要求公式重算結果 //..2014/03/26
 557:             sheet.ForceFormulaRecalculation = true;
 558:  
 559:             DataTable table = new DataTable();
 560:  
 561:             IRow headerRow = sheet.GetRow(HeaderRowIndex);
 562:             int cellCount = headerRow.LastCellNum;
 563:  
 564:             #region 取得資料欄位名稱
 565:             for (int i = headerRow.FirstCellNum; i < cellCount; i++)
 566:             {
 567:                 DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
 568:                 table.Columns.Add(column);
 569:             }
 570:             #endregion
 571:  
 572:             #region 取得資料內容
 573:             int rowCount = sheet.LastRowNum;
 574:             for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
 575:             {
 576:                 IRow row = sheet.GetRow(i);
 577:                 DataRow dataRow = table.NewRow();
 578:  
 579:                 for (int j = row.FirstCellNum; j < cellCount; j++)
 580:                 {
 581:                     if (row.GetCell(j) != null)
 582:                     {
 583:                         #region..2014/03/26  處理公式
 584:                         if (row.GetCell(j).CellType == CellType.FORMULA)
 585:                         {
 586:                             switch (row.GetCell(j).CachedFormulaResultType)
 587:                             {
 588:                                 case CellType.BLANK:
 589:                                     dataRow[j] = "BLANK";
 590:                                     break;
 591:                                 case CellType.BOOLEAN:
 592:                                     dataRow[j] = row.GetCell(j).StringCellValue;
 593:                                     break;
 594:                                 case CellType.ERROR:
 595:                                     dataRow[j] = "ERROR";
 596:                                     break;
 597:                                 case CellType.FORMULA:
 598:                                     dataRow[j] = row.GetCell(j).RichStringCellValue.ToString();
 599:                                     break;
 600:                                 case CellType.NUMERIC:
 601:                                     dataRow[j] = row.GetCell(j).NumericCellValue.ToString();
 602:                                     break;
 603:                                 case CellType.STRING:
 604:                                     dataRow[j] = row.GetCell(j).StringCellValue;
 605:                                     break;
 606:                                 case CellType.Unknown:
 607:                                     dataRow[j] = "Unknown";
 608:                                     break;
 609:                                 default:
 610:                                     break;
 611:                             }
 612:                         #endregion..2014/03/26  處理公式
 613:                         }
 614:                         else
 615:                         {
 616:                             dataRow[j] = row.GetCell(j).ToString();
 617:                         }
 618:                     }
 619:                 }
 620:  
 621:                 table.Rows.Add(dataRow);
 622:             }
 623:             #endregion
 624:  
 625:             ExcelFileStream.Close();
 626:             workbook = null;
 627:             sheet = null;
 628:             return table;
 629:         }
 630:  
 631:         //-----<< 擴充可寫入多個 SHEET 並修改SHEET NAME >>----
 632:         public static Stream RenderDataTableToExcel(List<SheetTable> SourceTables)
 633:         {
 634:             HSSFWorkbook hssfworkbook = new HSSFWorkbook();
 635:             MemoryStream ms = new MemoryStream();
 636:             List<ISheet> sheets = new List<ISheet>();
 637:             for (int k = 0; k < SourceTables.Count(); k++)
 638:             {
 639:                 ISheet sheet = hssfworkbook.CreateSheet();
 640:                 sheets.Add(sheet);
 641:             }
 642:             IRow headerRow;
 643:  
 644:  
 645:             for (int i = 0; i < SourceTables.Count(); i++)
 646:             {
 647:                 SheetTable Source = SourceTables[i];
 648:                 hssfworkbook.SetSheetName(i, Source.TableName); // 修改 Sheet Name.
 649:  
 650:                 #region ==[handling header]==
 651:                 headerRow = sheets[i].CreateRow(0);
 652:                 foreach (DataColumn column in Source.SourceTable.Columns)
 653:                 {
 654:                     headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
 655:                 }
 656:                 #endregion
 657:  
 658:                 #region ==[handling value]==
 659:                 int rowIndex = 1;
 660:  
 661:                 foreach (DataRow row in Source.SourceTable.Rows)
 662:                 {
 663:                     IRow dataRow = sheets[i].CreateRow(rowIndex);
 664:  
 665:                     foreach (DataColumn column in Source.SourceTable.Columns)
 666:                     {
 667:                         dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
 668:                     }
 669:  
 670:                     rowIndex++;
 671:                 }
 672:                 #endregion
 673:             }
 674:  
 675:             hssfworkbook.Write(ms);
 676:             ms.Flush();
 677:             ms.Position = 0;
 678:  
 679:             //sheet = null;
 680:             headerRow = null;
 681:             hssfworkbook = null;
 682:  
 683:             return ms;
 684:         }
 685:         public static void RenderDataTableToExcel(List<SheetTable> SourceTables, string FileName)
 686:         {
 687:             MemoryStream ms = RenderDataTableToExcel(SourceTables) as MemoryStream;
 688:             FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);
 689:             //FileStream fs = new FileStream(FileName, FileMode.Append, FileAccess.Write); //..在檔案存在時開啟它並搜尋至檔案末端,或建立新檔案
 690:  
 691:             byte[] data = ms.ToArray();
 692:  
 693:             fs.Write(data, 0, data.Length);
 694:             fs.Flush();
 695:             fs.Close();
 696:  
 697:             data = null;
 698:             ms = null;
 699:             fs = null;
 700:         }
 701:     }
 702:  
 703:     public class SheetTable
 704:     {
 705:         public SheetTable() { }
 706:         public SheetTable(DataTable table, string name)
 707:         {
 708:             SourceTable = table;
 709:             TableName = name;
 710:         }
 711:  
 712:         public DataTable SourceTable;
 713:         public string TableName;
 714:     }
 715: }



具體實現





 

 

 

   1: using System;
   2: using System.Collections;
   3: using System.Collections.Generic;
   4: using System.ComponentModel;
   5: using System.Data;
   6: using System.Drawing;
   7: using System.Linq;
   8: using System.Text;
   9:  
  10: using System.Windows.Forms;
  11: using System.IO.Ports;
  12: using System.IO;
  13: using System.Threading;
  14: using System.Diagnostics;//記得using
  15: using System.Reflection;//記得using
  16:  
  17: using Laser5Axis.Extension;
  18:  
  19:  
  20: namespace Laser5Axis.Test
  21: {
  22:     class test
  23:     {
  24:         List<RunData> RunDatas = new List<RunData>();
  25:  
  26:         public void Test()
  27:         {
  28:             //.. Save to File
  29:             RunData.SaveToFile(ref RunDatas, "test.bin");
  30:             RunData.SaveToXML(ref RunDatas, "test.xml");
  31:             RunData.ExportExcel(ref RunDatas, "test.xls", "sheet1");
  32:  
  33:             //.. Load from File
  34:             RunData.LoadFromFile(ref RunDatas, "test.bin");
  35:             RunData.LoadFromXML(ref RunDatas, "test.xml");
  36:             RunData.ImportExcel(ref RunDatas, "test.xls", "sheet1");
  37:         }
  38:  
  39:     }
  40:  
  41:  
  42:     [Serializable()]
  43:     public class RunData
  44:     {
  45:         /* 方法 */
  46:         public string getString()
  47:         {
  48:             string strRunLaser = RunLaser ? "1" : "0";
  49:             string Result = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}",
  50:                 X_Axis_Pos, X_Axis_Speed,
  51:                 Y_Axis_Pos, Y_Axis_Speed,
  52:                 Z_Axis_Pos, Z_Axis_Speed,
  53:                 S1_Axis_Pos, S1_Axis_Speed,
  54:                 S2_Axis_Pos, S2_Axis_Speed,
  55:                 Z_SafePos, strRunLaser,
  56:                 SelectCAD
  57:                  );
  58:             return Result;
  59:         }
  60:         public static void LoadFromFile(ref List<RunData> list, string FileName)
  61:         {
  62:             list = list.binLoadFromDisk(FileName);
  63:         }
  64:         public static void SaveToFile(ref List<RunData> list, string FileName)
  65:         {
  66:             list.binSaveToDisk(FileName);
  67:         }
  68:         public static void LoadFromXML(ref List<RunData> list, string FileName)
  69:         {
  70:             list = list.xmlLoadFromDisk(FileName);
  71:         }
  72:         public static void SaveToXML(ref List<RunData> list, string FileName)
  73:         {
  74:             list.xmlSaveToDisk(FileName);
  75:         }
  76:         public static void ExportExcel(ref List<RunData> list, string FileName, string sheetName)
  77:         {
  78:             list.ExportExcel(FileName, sheetName);
  79:         }
  80:         public static void ImportExcel(ref List<RunData> list, string FileName, string SheetName)
  81:         {
  82:             list = list.ImportExcel(FileName, SheetName); //尚有轉型問題
  83:         }
  84:  
  85:  
  86:         /* 屬性 */
  87:         public int Z_SafePos { get; set; }
  88:  
  89:         public int X_Axis_Pos { get; set; }
  90:         public int Y_Axis_Pos { get; set; }
  91:         public int Z_Axis_Pos { get; set; }
  92:         public int S1_Axis_Pos { get; set; }
  93:         public int S2_Axis_Pos { get; set; }
  94:  
  95:         public int X_Axis_Speed { get; set; }
  96:         public int Y_Axis_Speed { get; set; }
  97:         public int Z_Axis_Speed { get; set; }
  98:         public int S1_Axis_Speed { get; set; }
  99:         public int S2_Axis_Speed { get; set; }
 100:  
 101:         public bool RunLaser { get; set; }
 102:         public string SelectCAD { get; set; }
 103:     }
 104:  
 105: }

沒有留言:

張貼留言