读取Excel得到DataTable
1 using Microsoft.Office.Interop.Excel; 2 using System; 3 using System.Data; 4 using System.Diagnostics; 5 6 namespace ExcelToData 7 { 8 public class ExcelHelper 9 { 10 private static Stopwatch wath = new Stopwatch(); 11 12 /// <summary> 13 /// 使用COM读取Excel 14 /// </summary> 15 /// <param name="excelFilePath">路径</param> 16 /// <returns>DataTabel</returns> 17 public static System.Data.DataTable GetExcelData(string excelFilePath) 18 { 19 Application app = new Application(); 20 Sheets sheets; 21 Workbook workbook = null; 22 object oMissiong = System.Reflection.Missing.Value; 23 System.Data.DataTable dt = new System.Data.DataTable(); 24 25 wath.Start(); 26 27 try 28 { 29 if (app == null) 30 { 31 return null; 32 } 33 34 workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong); 35 36 //将数据读入到DataTable中——Start 37 38 sheets = workbook.Worksheets; 39 Worksheet worksheet = (Worksheet)sheets.get_Item(1);//读取第一张表 40 if (worksheet == null) 41 return null; 42 43 string cellContent; 44 int iRowCount = worksheet.UsedRange.Rows.Count; 45 int iColCount = worksheet.UsedRange.Columns.Count; 46 Range range; 47 48 //负责列头Start 49 DataColumn dc; 50 int ColumnID = 1; 51 range = (Range)worksheet.Cells[1, 1]; 52 while (!string.IsNullOrEmpty(range.Text.ToString().Trim())) 53 { 54 dc = new DataColumn(); 55 dc.DataType = System.Type.GetType("System.String"); 56 dc.ColumnName = range.Text.ToString().Trim(); 57 dt.Columns.Add(dc); 58 59 range = (Range)worksheet.Cells[1, ++ColumnID]; 60 } 61 //End 62 63 for (int iRow = 2; iRow <= iRowCount; iRow++) 64 { 65 DataRow dr = dt.NewRow(); 66 67 for (int iCol = 1; iCol <= iColCount; iCol++) 68 { 69 range = (Range)worksheet.Cells[iRow, iCol]; 70 71 cellContent = (range.Value2 == null) ? "" : range.Text.ToString(); 72 73 dr[iCol - 1] = cellContent; 74 } 75 76 dt.Rows.Add(dr); 77 } 78 79 wath.Stop(); 80 TimeSpan ts = wath.Elapsed; 81 82 //将数据读入到DataTable中——End 83 return dt; 84 } 85 catch 86 { 87 88 return null; 89 } 90 finally 91 { 92 workbook.Close(false, oMissiong, oMissiong); 93 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); 94 workbook = null; 95 app.Workbooks.Close(); 96 app.Quit(); 97 System.Runtime.InteropServices.Marshal.ReleaseComObject(app); 98 app = null; 99 GC.Collect(); 100 GC.WaitForPendingFinalizers(); 101 } 102 } 103 } 104 }
分享每天的收获之一种快乐。