程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> C#如何獲取Excel工作薄中Sheet頁(工作表)名集合

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

編輯:關於C#
#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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved