摘要:讀取Excel檔案裡面的内容到DataSet
代碼:
1 /// <summary>
2 /// 讀取Excel檔案裡面的内容到DataSet
3 /// </summary>
4 /// <param name="Path"></param>
5 /// <param name="ds"></param>
6 private void ExcelToDS(string Path,ref DataSet ds)
7 {
8 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
9 OleDbConnection conn = new OleDbConnection(strConn);
10 conn.Open();
11
12 //傳回Excel的架構,包括各個sheet表的名稱,類型,建立時間和修改時間等
13 DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
14
15 //包含excel中表名的字元串數組
16 string[] strTableNames = new string[dtSheetName.Rows.Count];
17 for (int k = 0; k < dtSheetName.Rows.Count; k++)
18 {
19 strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
20 }
21
22 string strExcel = "";
23 OleDbDataAdapter myCommand = null;
24 strExcel = "select * from [" + strTableNames[0] + "]";//strTableNames[0]取得第一個Sheet中的資料
25 myCommand = new OleDbDataAdapter(strExcel, strConn);
26 ds = new DataSet();
27 myCommand.Fill(ds);
28 conn.Close();
29 conn.Dispose();
30 }
如果您看了本篇部落格,覺得對您有所收獲,請點選右下角的
[推薦]如果您想轉載本部落格,
請注明出處如果您對本文有意見或者建議,歡迎留言
感謝您的閱讀,請關注我的後續部落格