今天发现一个好的连接excel文件的操作,以前操作excel导入一般要求表格的表名为sheet1等。下面代码可以自动获得excel表格中第一个sheet的名称。代码如下:
| 以下是代码片段: string filepath = Server.MapPath(hidFilePath.Value);
string conn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + filepath + ";Extended Properties=Excel 8.0"; OleDbConnection thisconnection = new OleDbConnection(conn); thisconnection.Open(); DataTable dt = thisconnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string firstTable = dt.Rows[0][2].ToString().Trim(); string Sql = "select * from [" + firstTable + "]"; OleDbDataAdapter mycommand = new OleDbDataAdapter(Sql, thisconnection); DataSet ds = new DataSet(); mycommand.Fill(ds, "[" + firstTable + "]"); thisconnection.Close(); |
说明:thisconnection.GetOleDbSchemaTable,是取得excel文件中sheet的集合(以表格的形式返回)
这样我们就能知道excel文件中有什么样子的内容啦。

当前 位置: 
