C# 讀取Excel中的資料
#region 讀取Excel中的資料 /// <summary> /// 讀取Excel中的資料 /// </summary> /// <param name="excelFile">Excel檔案名稱及路徑,EG:C:\Users\JK\Desktop\匯入測試.xls</param> /// <returns>Excel中的資料</returns> private DataTable GetTable(string fileName) { OleDbConnection objConn = null; System.Data.DataTable dt = null; string connString = string.Empty; OleDbDataAdapter da = new OleDbDataAdapter(); //擷取Excel工作薄中Sheet頁(工作表)名集合 String[] ss = this.GetExcelSheetNames(fileName); DataTable dataTable = new DataTable(); try { string FileType = fileName.Substring(fileName.LastIndexOf(".")); if (FileType == ".xls") connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";Extended Properties=Excel 8.0;"; else//.xlsx connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; // 建立連線物件 objConn = new OleDbConnection(connString); // 開啟資料庫連接 objConn.Open(); string sql_F = "Select * FROM [{0}]"; for (int i = 0; i < ss.Length;i++ ) { da.SelectCommand = new OleDbCommand(String.Format(sql_F, ss[i].ToString() + "$"), objConn); da.Fill(dataTable); MessageBox.Show("第"+i+"次表中資料量="+dataTable.Rows.Count.ToString()); } dataTable = DeleteBlank(dataTable,9); MessageBox.Show("刪除空行後,表中資料量=" + dataTable.Rows.Count.ToString()); return dataTable; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return null; } finally { // 清理 if (objConn != null) { objConn.Close(); objConn.Dispose(); } if (dt != null) { dt.Dispose(); } } } #endregion
#region 刪除指定表中的空白行 /// <summary> ///刪除指定表中的空白行 /// </summary> /// <param name="dt">表名</param> /// <param name="ColNum">Excel中的列數</param> /// <returns>刪除空白行後的DataTable</returns> private DataTable DeleteBlank(DataTable dt,int ColNum) { if (dt == null || dt.Rows.Count==0) { return dt; } //刪除其中的空行(注意for迴圈的形式) for (int i = dt.Rows.Count - 1; i >= 0; i--) { DataRow row = dt.Rows[i]; bool flag = true; //當某行的ColNum列,均為空白時,改行為空白 for (int j = 0; j < ColNum; j++) { object o = row[j]; if (o != DBNull.Value && Convert.ToString(o).Trim().Length > 0) { flag = false; break; } } if (flag) { dt.Rows[i].Delete(); } } dt.AcceptChanges(); //把行中DBNull列替換成Null 字元串 for (int k = dt.Rows.Count - 1; k >= 0; k--) { DataRow row = dt.Rows[k]; for (int z = 0; z < ColNum; z++) { object o = row[z]; if (o == DBNull.Value) { if (dt.Columns[z].DataType == typeof(string)) { row[z] = ""; } } } } dt.AcceptChanges(); return dt; } #endregion
小註:
讀取Excel的時候,會自動處理表頭。
以上就是C# 讀取Excel中的資料的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!