asp教程.net c#取excel 合并單元格內容讀取excel數據,填充dataset// 連接字符串 string xlspath = server.mappath("~/www.111cn.net/somefile.xls");string connstr = " oledbconnection conn = null;oledbdataadapter da = null;datatable tblschema = null;ilist<string> tblnames = null; // 初始化連接,并打開conn = new oledbconnection(connstr);conn.open(); // 獲取數據源的表定義元數據 //tblschema = conn.getschema("tables");tblschema = conn.getoledbschematable(oledbschemaguid.tables, new object[] { null, null, null, "table" }); //gridview1.datasource = tblschema;//gridview1.databind(); // 關閉連接//conn.close(); tblnames = new list<string>();foreach (datarow row in tblschema.rows) {tblnames.add((string)row["table_name"]); // 讀取表名} // 初始化適配器da = new oledbdataadapter();// 準備數據,導入datasetdataset ds = new dataset(); foreach (string tblname in tblnames) {da.selectcommand = new oledbcommand(string.format(sql_f, tblname), conn);try {da.fill(ds, tblname);}catch {// 關閉連接if (conn.state == connectionstate.open) {conn.close();}throw;}} // 關閉連接(www.111cn.net)if (conn.state == connectionstate.open) {conn.close();} // 對導入dataset的每張sheet進行處理 // 這里僅做顯示gridview1.datasource = ds.tables[0];gridview1.databind(); gridview2.datasource = ds.tables[1];gridview2.databind(); // more codes// .這里我們就不需要對selec 語句進行"硬編碼",可以根據需要動態的構造from 字句的"表名"。 不僅可以,獲取表明,還可以獲取每張表內的字段名、字段類型等信息:tblschema = conn.getoledbschematable(oledbschemaguid.columns, new object[] { null, null, null, null });在ado.net 1.x 時候只有oledb提供了getoledbschematable 方法,而sqlclient或者orcaleclient沒有對應的方法,因為對應數據庫教程已經提供了類似功能的存儲過程或者系統表供應用程序訪問,比如對于sql server: select *from northwind.information_schema.columnswhere table_name = n'customers' 而在ado.net 2.0中每個xxxconnenction都實現了基類system.data.common.dbconnection的 getschemal private dataset binddsfromexcel(string strfiledir, string strdataname){string strconn;strconn = "provider=microsoft.jet.oledb.4.0;data source=" + strfiledir + ";extended properties='excel 8.0;hdr=false;imex=1'";oledbconnection oleconn = new oledbconnection(strconn);oleconn.open();string sql = "select * from [" + strdataname + "$]";//如果不知道名字就用sheets[1] oledbdataadapter oledaexcel = new oledbdataadapter(sql, oleconn);dataset oledsexcle = new dataset();oledaexcel.fill(oledsexcle, strdataname);oleconn.close();return oledsexcle;}from:http://www.111cn.net/net/net/35137.htm
新聞熱點
疑難解答