asp.net C#取Excel 合并单元格内容

asp教程.net c#取excel 合并单元格内容

读取excel数据,填充dataset

// 连接字符串

string xlspath = server.mappath("~/www.111cn.net/somefile.xls");

string connstr = "provider=microsoft.jet.oledb.4.0;" +

"extended properties="excel 8.0;hdr=no;imex=1";" + // 指定扩展属性为 microsoft excel 8.0 (97) 9.0 (2000) 10.0 (2002),并且第一行作为数据返回,且以文本方式读取

"data source=" + xlspath;

string sql_f = "select * from [{0}]";

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();

// 准备数据,导入dataset

dataset 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.columns

where 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