C#读取Excel的三种方式以及比较分析

2019-12-30 11:04:22王冬梅
  • dt.Columns.Add(dc);   
  • range = (Excel.Range)worksheet.Cells[1, ++ColumnID];  } 
  • //End  for (int iRow = 2; iRow <= iRowCount; iRow++) 
  • {  DataRow dr = dt.NewRow(); 
  • for (int iCol = 1; iCol <= iColCount; iCol++)  { 
  • range = (Excel.Range)worksheet.Cells[iRow, iCol];  cellContent = (range.Value2 == null) ? "" : range.Text.ToString(); 
  • dr[iCol - 1] = cellContent;  } 
  • dt.Rows.Add(dr);  } 
  • wath.Stop();  TimeSpan ts = wath.Elapsed; 
  • //将数据读入到DataTable中——End  return dt; 
  • }  catch 
  • {  return null; 
  • }  finally 
  • {  workbook.Close(false, oMissiong, oMissiong); 
  • System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);  workbook = null; 
  • app.Workbooks.Close();  app.Quit(); 
  • System.Runtime.InteropServices.Marshal.ReleaseComObject(app);  app = null; 
  • GC.Collect();  GC.WaitForPendingFinalizers(); 
  • }  } 
  • /// <summary>  /// 使用COM,多线程读取Excel(1 主线程、4 副线程) 
  • /// </summary>  /// <param name="excelFilePath">路径</param> 
  • /// <returns>DataTabel</returns>  public System.Data.DataTable ThreadReadExcel(string excelFilePath) 
  • {  Excel.Application app = new Excel.Application(); 
  • Excel.Sheets sheets = null;  Excel.Workbook workbook = null; 
  • object oMissiong = System.Reflection.Missing.Value;  System.Data.DataTable dt = new System.Data.DataTable(); 
  • wath.Start();  try 
  • {  if (app == null) 
  • {  return null; 
  • }  workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong,