讀取Excel裏面的內容轉為DataTable
阿新 • • 發佈:2018-11-01
namespace empty shee open() provider bsp emp data except
using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Linq; using System.Text; namespace ExcelRead { class ExcelHelper { private static string excelConstr; private OleDbConnection conn = null;//操作數據庫 private OleDbDataAdapter ada = null;//填充dataset public ExcelHelper(string path) { excelConstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties = Excel 12.0"; if (conn == null || conn.State == ConnectionState.Closed) { conn = new OleDbConnection(excelConstr); } } public DataTable GetDataSource(string sheetName) { DataTable dt = new DataTable(); string sql = string.Empty; sql = "select * from [" + sheetName + "]"; dt = GetDT(sql); return dt; } /// <summary> /// 獲取excel數據 /// </summary> /// <param name="sql">用於查詢的sql</param> /// <returns></returns> public DataTable GetDT(string sql) { DataSet ds = new DataSet(); try { if (conn.State == ConnectionState.Closed) { conn.Open(); } ada = new OleDbDataAdapter(sql, conn); ada.Fill(ds); } catch (Exception e) { throw e; } finally { conn.Close(); } return ds.Tables[0]; } } }
//獲取Excel表裏Sheet1的數據
//調用 ExcelHelper _excelhelper = new ExcelHelper("Excel文件路徑"); //Excel的sheet名稱,後面要跟$符號 _excelhelper.GetDataSource("Sheet1$");
讀取Excel裏面的內容轉為DataTable