C#如何擷取Excel工作薄中Sheet頁(工作表)名集合

來源:互聯網
上載者:User
#region 擷取Excel工作薄中Sheet頁(工作表)名集合   
02./// <summary>
03./// 擷取Excel工作薄中Sheet頁(工作表)名集合
04./// </summary>
05./// <param name="excelFile">Excel檔案名稱及路徑,EG:C:\Users\JK\Desktop\匯入測試.xls</param>
06./// <returns>Sheet頁名稱集合</returns>
07.private String[] GetExcelSheetNames(string fileName)
08.{
09. OleDbConnection objConn = null;
10. System.Data.DataTable dt = null;
11. try
12. {
13. string connString=string.Empty;
14. string FileType =fileName.Substring(fileName.LastIndexOf("."));
15. if (FileType == ".xls")
16. connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
17. "Data Source=" + fileName + ";Extended Properties=Excel 8.0;";
18. else//.xlsx
19. connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
20. // 建立連線物件
21. objConn = new OleDbConnection(connString);
22. // 開啟資料庫連接
23. objConn.Open();
24. // 得到包含資料架構的資料表
25. dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
26. if (dt == null)
27. {
28. return null;
29. }
30. String[] excelSheets = new String[dt.Rows.Count];
31. int i = 0;
32. // 添加工作表名稱到字串數組
33. foreach (DataRow row in dt.Rows)
34. {
35. string strSheetTableName = row["TABLE_NAME"].ToString();
36. //過濾無效SheetName
37. if (strSheetTableName.Contains("$")&&strSheetTableName.Replace("'", "").EndsWith("$"))
38. {
39. excelSheets[i] = strSheetTableName.Substring(0, strSheetTableName.Length - 1);
40. }
41. i++;
42. }
43. return excelSheets;
44. }
45. catch (Exception ex)
46. {
47. MessageBox.Show(ex.ToString());
48. return null;
49. }
50. finally
51. {
52. // 清理
53. if (objConn != null)
54. {
55. objConn.Close();
56. objConn.Dispose();
57. }
58. if (dt != null)
59. {
60. dt.Dispose();
61. }
62. }
63.}
64.#endregion

本文URL:http://www.bianceng.cn/Programming/csharp/201410/45597.htm

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.