C#讀取Excel數(shù)據(jù)簡(jiǎn)析
C#讀取Excel數(shù)據(jù)之讀取Excel工作薄中指定區(qū)域的單元格數(shù)據(jù)
使用ADO.NET中的OleDbDataAdapter對(duì)象讀取Excel文件,默認(rèn)工作表中的有數(shù)據(jù)的第一行單元格為字段名稱(chēng)。如果不想將工作薄中有數(shù)據(jù)的第一行單元格當(dāng)作數(shù)據(jù)表字段名,可以用本文中的第二個(gè)實(shí)例實(shí)現(xiàn)。
C#讀取Excel數(shù)據(jù)的實(shí)現(xiàn):建立Connection對(duì)象的數(shù)據(jù)源連接字符串:"Provider=Microsoft.Jet.Oledb.4.0;Data Source=Excel 文件物理路徑 + ";Extended Properties=Excel 8.0"; 這兩個(gè)實(shí)例用Excel 2000以上版本制作。
C#讀取Excel數(shù)據(jù)實(shí)例1、讀取Excel工作薄中的全部數(shù)據(jù)
讀取Excel工作薄1(工作薄名稱(chēng):Sheet1)中的全部數(shù)據(jù),在OleDbDataAdapter對(duì)象中的SQL語(yǔ)句應(yīng)為:"Select 字段列表 From [工作表名$]"。
C#讀取Excel數(shù)據(jù)代碼示例:
- public void ReadExcel(string sExcelFile)
- {
- string sConnectionString = "Provider=Microsoft.Jet.Oledb.4.0;
- Data Source=" + sExcelFile + ";Extended Properties=Excel 8.0";
- OleDbConnection connection = new OleDbConnection(sConnectionString);
- OleDbDataAdapter adp = new OleDbDataAdapter(
- "Select * from [Sheet1$]",connection);
- DataSet ds = new DataSet();
- adp.Fill(ds,"Book1");
- grd_Excel.DataSource = ds.Tables["Book1"].DefaultView;
- grd_Excel.DataBind();
- }
C#讀取Excel數(shù)據(jù)實(shí)例2、讀取Excel工作薄選定區(qū)域中的數(shù)據(jù)
首先在工作簿中,左鍵拖拽選取要定義成為表的區(qū)域,從菜單中選擇‘插入’->‘名稱(chēng)’->‘定義’,在‘定義名稱(chēng)’對(duì)話框出現(xiàn)中鍵入表的名字:“TestTable”,OK。
那么SQL語(yǔ)句應(yīng)為:SELECT * FROM TestTable。
C#讀取Excel數(shù)據(jù)代碼示例:
- public void ReadExcel(string sExcelFile)
- {
- string sConnectionString = "Provider=Microsoft.Jet.Oledb.4.0;
- Data Source=" + sExcelFile + ";Extended Properties=Excel 8.0";
- OleDbConnection connection = new OleDbConnection(sConnectionString);
- OleDbDataAdapter adp = new OleDbDataAdapter(
- "SELECT * FROM TestTable", connection);
- DataSet ds = new DataSet();
- adp.Fill(ds,"Book1");
- grd_Excel.DataSource = ds.Tables["Book1"].DefaultView;
- grd_Excel.DataBind();
- }
C#讀取Excel數(shù)據(jù)的基本情況就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C#讀取Excel數(shù)據(jù)有所幫助。
【編輯推薦】