ADO.NET 读取Excel文件示例

 1 private DataSet LoadFile(string fileName) 
2 {
3 DataSet ret = new DataSet();
4 System.Data.OleDb.OleDbConnection myConnection = new System.Data.OleDb.OleDbConnection();
5 //You should consider using "HDR=NO", to get numbered ColumnNames in your DataSet.
6 myConnection.ConnectionString =
7 string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Persist Security Info=False;Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"", fileName);
8 //Try-Catch-Finally? myConnection.Open();
9 //Get all Table-Names from the workbook
10 DataTable tbl = myConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
11 foreach (DataRow row in tbl.Rows)
12 {
13 string tableName = row[2].ToString();
14 System.Data.OleDb.OleDbCommand selectCommand = new System.Data.OleDb.OleDbCommand(string.Format("SELECT * FROM [{0}]", tableName), myConnection);
15 System.Data.OleDb.OleDbDataAdapter myAdapter = new System.Data.OleDb.OleDbDataAdapter(selectCommand);
16 myAdapter.Fill(ret, tableName);
17 }
18 myConnection.Close();
19 return ret;
20 }
posted @ 2011-09-24 10:59  Max Woods  阅读(436)  评论(0编辑  收藏  举报