程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#讀取Excel的三種方法和比擬剖析

C#讀取Excel的三種方法和比擬剖析

編輯:C#入門知識

C#讀取Excel的三種方法和比擬剖析。本站提示廣大學習愛好者:(C#讀取Excel的三種方法和比擬剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是C#讀取Excel的三種方法和比擬剖析正文


(1)OleDB方法

長處:將Excel直接當作數據源處置,經由過程SQL直接讀取內容,讀取速度較快。

缺陷:讀取數據方法不敷靈巧,沒法直接讀取某一個單位格,只要將全部Sheet頁讀掏出來後(成果為Datatable)再在Datatable中依據行列數來獲得指定的值。

當Excel數據量很年夜時。會異常占用內存,當內存不敷時會拋出內存溢出的異常。

讀代替碼以下:

 public DataTable GetExcelTableByOleDB(string strExcelPath, string tableName)
 {
   try
   {
     DataTable dtExcel = new DataTable();
     //數據表
     DataSet ds = new DataSet();
     //獲得文件擴大名
     string strExtension = System.IO.Path.GetExtension(strExcelPath);
     string strFileName = System.IO.Path.GetFileName(strExcelPath);
     //Excel的銜接
     OleDbConnection objConn = null;
     switch (strExtension)
     {
       case ".xls":
         objConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strExcelPath + ";" + "Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;\"");
         break;
       case ".xlsx":
         objConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelPath + ";" + "Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1;\"");
         break;
       default:
         objConn = null;
         break;
     }
     if (objConn == null)
     {
       return null;
     }
     objConn.Open();
     //獲得Excel中一切Sheet表的信息
     //System.Data.DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
     //獲得Excel的第一個Sheet表名
     //string tableName = schemaTable.Rows[0][2].ToString().Trim();
     string strSql = "select * from [" + tableName + "]";
     //獲得Excel指定Sheet表中的信息
     OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
     OleDbDataAdapter myData = new OleDbDataAdapter(strSql, objConn);
     myData.Fill(ds, tableName);//填湊數據
     objConn.Close();
     //dtExcel即為excel文件中指定表中存儲的信息
     dtExcel = ds.Tables[tableName];
     return dtExcel;
   }
   catch
   {
     return null;
   }
 }

上面解釋一下銜接字符串

HDR=Yes,這代表第一行是題目,不做為數據應用(然則我在現實應用中,假如第一行存在龐雜數值,那末讀獲得到的Datatable列題目會主動設置為F1、F2等方法定名,與現實運用不符,所以其時是經由過程HDR=No方法將一切內容讀取到Datatable中,然背工動將第一行設置成題目的);IMEX ( IMport EXport mode )設置
IMEX 有三種形式:
0 is Export mode
1 is Import mode
2 is Linked mode (full update capabilities)
我這裡特殊要解釋的就是 IMEX 參數了,由於分歧的形式代表著分歧的讀寫行動:
當 IMEX=0 時為“匯出形式”,這個形式開啟的 Excel 檔案只能用來做“寫入”用處。
當 IMEX=1 時為“匯入形式”,這個形式開啟的 Excel 檔案只能用來做“讀取”用處。
當 IMEX=2 時為“鏈接形式”,這個形式開啟的 Excel 檔案可同時增援“讀取”與“寫入”用處。

---------------------------------

別的,讀取Excel2007版本的文件時,版本應當從8.0改成12.0,同時驅動不克不及再用Jet,而應當用ACE。擔任會形成“找不到可裝置的 ISAM”的毛病。

---------------------------------

在網上還發明采取這類方法存在掏出的Sheet表的個數多於現實Excel表中的Sheet表個數的情形,其緣由有二:

1. 掏出的稱號中,包含了XL定名治理器中的稱號(拜見XL2007的公式--定名治理器, 快捷鍵Crtl+F3);

2. 掏出的稱號中,包含了FilterDatabase後綴的, 這是XL用來記載Filter規模的。

關於第一點比擬簡略, 刪除已有定名治理器中的內容便可;第二點處置起來比擬費事, Filter刪除後這些稱號仍然保存著,簡略的做法是新增Sheet然後將原Sheet Copy出來。但現實情形其實不能為每一個Excel做以上檢討。上面給出了過濾的計劃。(此成績我們有驗證過,年夜家本身驗證一下吧)

 //objConn為讀取Excel的鏈接,上面經由過程過濾來獲得有用的Sheet頁稱號聚集
  System.Data.DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
  List<string> lstSheetNames = new List<string>();
  for (int i = 0; i < schemaTable.Rows.Count; i++)
  {
    string strSheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];
    if (strSheetName.Contains("$") && !strSheetName.WordStr("'", "").EndsWith("$"))
    {
      //過濾有效SheetName終了....
      continue;
    }
    if (lstSheetNames != null && !lstSheetNames.Contains(strSheetName))
      lstSheetNames.Add(strSheetName);
  }

由於讀掏出來有效SheetName普通情形最初一個字符都不會是$。假如SheetName有一些特別符號,讀掏出來的SheetName會主動加上單引號。好比在Excel中將SheetName編纂成MySheet(1),此時讀掏出來的SheetName就為:'MySheet(1)$',所以斷定最初一個字符是否是$之前最好過濾一下單引號。

---------------------------------

(2)Com組件的方法(經由過程添加 Microsoft.Office.Interop.Excel援用完成)

長處:可以或許異常靈巧的讀取Excel中的數據,用戶可以靈巧的挪用各類函數停止處置。

缺陷:基於單位格的處置,讀取速度較慢,關於數據量較年夜的文件最好不要應用此種方法讀取。

須要添加響應的DLL援用,必需存在此援用才可以使用,假如是Web站點安排在IIS上時,還須要辦事器機子已裝置了Excel,有時刻還須要為設置裝備擺設IIS權限。

讀代替碼以下:

 private Stopwatch wath = new Stopwatch();
 /// <summary>
 /// 應用COM讀取Excel
 /// </summary>
 /// <param name="excelFilePath">途徑</param>
 /// <returns>DataTabel</returns>
 public System.Data.DataTable GetExcelData(string excelFilePath)
 {
   Excel.Application app = new Excel.Application();
   Excel.Sheets sheets;
   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, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
     //將數據讀入到DataTable中——Start  
     sheets = workbook.Worksheets;
     Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);//讀取第一張表
     if (worksheet == null)
       return null;
     string cellContent;
     int iRowCount = worksheet.UsedRange.Rows.Count;
     int iColCount = worksheet.UsedRange.Columns.Count;
     Excel.Range range;
     //擔任列頭Start
     DataColumn dc;
     int ColumnID = 1;
     range = (Excel.Range)worksheet.Cells[1, 1];
     while (range.Text.ToString().Trim() != "")
     {
       dc = new DataColumn();
       dc.DataType = System.Type.GetType("System.String");
       dc.ColumnName = range.Text.ToString().Trim();
       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, 
       oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
     //將數據讀入到DataTable中——Start  
     sheets = workbook.Worksheets;
     Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);//讀取第一張表
     if (worksheet == null)
       return null;
     string cellContent;
     int iRowCount = worksheet.UsedRange.Rows.Count;
     int iColCount = worksheet.UsedRange.Columns.Count;
     Excel.Range range;
     //擔任列頭Start
     DataColumn dc;
     int ColumnID = 1;
     range = (Excel.Range)worksheet.Cells[1, 1];
     while (iColCount >= ColumnID)
     {
       dc = new DataColumn();
       dc.DataType = System.Type.GetType("System.String");
       string strNewColumnName = range.Text.ToString().Trim();
       if (strNewColumnName.Length == 0) strNewColumnName = "_1";
       //斷定列名能否反復
       for (int i = 1; i < ColumnID; i++)
       {
         if (dt.Columns[i - 1].ColumnName == strNewColumnName)
           strNewColumnName = strNewColumnName + "_1";
       }
       dc.ColumnName = strNewColumnName;
       dt.Columns.Add(dc);
       range = (Excel.Range)worksheet.Cells[1, ++ColumnID];
     }
     //End
     //數據年夜於500條,應用多過程停止讀取數據
     if (iRowCount - 1 > 500)
     {
       //開端多線程讀取數據
       //新建線程
       int b2 = (iRowCount - 1) / 10;
       DataTable dt1 = new DataTable("dt1");
       dt1 = dt.Clone();
       SheetOptions sheet1thread = new SheetOptions(worksheet, iColCount, 2, b2 + 1, dt1);
       Thread othread1 = new Thread(new ThreadStart(sheet1thread.SheetToDataTable));
       othread1.Start();
       //壅塞 1 毫秒,包管第一個讀取 dt1
       Thread.Sleep(1);
       DataTable dt2 = new DataTable("dt2");
       dt2 = dt.Clone();
       SheetOptions sheet2thread = new SheetOptions(worksheet, iColCount, b2 + 2, b2 * 2 + 1, dt2);
       Thread othread2 = new Thread(new ThreadStart(sheet2thread.SheetToDataTable));
       othread2.Start();
       DataTable dt3 = new DataTable("dt3");
       dt3 = dt.Clone();
       SheetOptions sheet3thread = new SheetOptions(worksheet, iColCount, b2 * 2 + 2, b2 * 3 + 1, dt3);
       Thread othread3 = new Thread(new ThreadStart(sheet3thread.SheetToDataTable));
       othread3.Start();
       DataTable dt4 = new DataTable("dt4");
       dt4 = dt.Clone();
       SheetOptions sheet4thread = new SheetOptions(worksheet, iColCount, b2 * 3 + 2, b2 * 4 + 1, dt4);
       Thread othread4 = new Thread(new ThreadStart(sheet4thread.SheetToDataTable));
       othread4.Start();
       //主線程讀取殘剩數據
       for (int iRow = b2 * 4 + 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);
       }
       othread1.Join();
       othread2.Join();
       othread3.Join();
       othread4.Join();
       //將多個線程讀掏出來的數據追加至 dt1 前面
       foreach (DataRow dr in dt.Rows)
         dt1.Rows.Add(dr.ItemArray);
       dt.Clear();
       dt.Dispose();
       foreach (DataRow dr in dt2.Rows)
         dt1.Rows.Add(dr.ItemArray);
       dt2.Clear();
       dt2.Dispose();
       foreach (DataRow dr in dt3.Rows)
         dt1.Rows.Add(dr.ItemArray);
       dt3.Clear();
       dt3.Dispose();
       foreach (DataRow dr in dt4.Rows)
         dt1.Rows.Add(dr.ItemArray);
       dt4.Clear();
       dt4.Dispose();
       return dt1;
     }
     else
     {
       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);
     System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
     workbook = null;
     app.Workbooks.Close();
     app.Quit();
     System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
     app = null;
     GC.Collect();
     GC.WaitForPendingFinalizers();
   }
 }

(3)NPOI方法讀取Excel(此辦法未經由測試)

NPOI 是 POI 項目標 .NET 版本。POI是一個開源的Java讀寫Excel、WORD等微軟OLE2組件文檔的項目。應用 NPOI 你便可以在沒有裝置 Office 或許響應情況的機械上對 WORD/EXCEL 文檔停止讀寫。

長處:讀取Excel速度較快,讀取方法操作靈巧性

缺陷:須要下載響應的插件並添加到體系援用傍邊。

 /// <summary>
 /// 將excel中的數據導入到DataTable中
 /// </summary>
 /// <param name="sheetName">excel任務薄sheet的稱號</param>
 /// <param name="isFirstRowColumn">第一行能否是DataTable的列名</param>
 /// <returns>前往的DataTable</returns>
 public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
 {
   ISheet sheet = null;
   DataTable data = new DataTable();
   int startRow = 0;
   try
   {
     fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
     if (fileName.IndexOf(".xlsx") > 0) // 2007版本
       workbook = new XSSFWorkbook(fs);
     else if (fileName.IndexOf(".xls") > 0) // 2003版本
       workbook = new HSSFWorkbook(fs);
     if (sheetName != null)
     {
       sheet = workbook.GetSheet(sheetName);
     }
     else
     {
       sheet = workbook.GetSheetAt(0);
     }
     if (sheet != null)
     {
       IRow firstRow = sheet.GetRow(0);
       int cellCount = firstRow.LastCellNum; //一行最初一個cell的編號 即總的列數
       if (isFirstRowColumn)
       {
         for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
         {
           DataColumn column = new DataColumn(firstRow.GetCell(i).StringCellValue);
           data.Columns.Add(column);
         }
         startRow = sheet.FirstRowNum + 1;
       }
       else
       {
         startRow = sheet.FirstRowNum;
       }
       //最初一列的標號
       int rowCount = sheet.LastRowNum;
       for (int i = startRow; i <= rowCount; ++i)
       {
         IRow row = sheet.GetRow(i);
         if (row == null) continue; //沒稀有據的行默許是null       
         
         DataRow dataRow = data.NewRow();
         for (int j = row.FirstCellNum; j < cellCount; ++j)
         {
           if (row.GetCell(j) != null) //同理,沒稀有據的單位格都默許是null
             dataRow[j] = row.GetCell(j).ToString();
         }
         data.Rows.Add(dataRow);
       }
     }
     return data;
   }
   catch (Exception ex)
   {
     Console.WriteLine("Exception: " + ex.Message);
     return null;
   }
 }

上面是一些相干的文章,年夜家可以參考下

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved