2014-10-17 76 views
1

使用Oledb,是否可以在Excel中獲取特殊工作表的所有NamedRanges?C# - 使用Oledb獲取Excel中特定工作表的名稱範圍

我寫了下面的代碼,它給了我NamedRanges,但我無法弄清楚NamedRange引用哪張表。

private String[] GetExcelSheetNames(string excelFilePath) 
{ 
    OleDbConnection objConn = null; 
    System.Data.DataTable dt = null; 

    try 
    { 
     //String connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFile + ";Extended Properties=Excel 12.0;"; 

     string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0", excelFilePath); 
     objConn = new OleDbConnection(connectionString); 
     objConn.Open(); 

     // Get the data table containg the schema guid. 
     dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables_Info, null); 

     if (dt == null) 
      return null; 

     String[] excelSheets = new String[dt.Rows.Count]; 
     int i = 0; 

     // Add the sheet name to the string array. 
     foreach (DataRow row in dt.Rows) 
      excelSheets[i++] = row["TABLE_NAME"].ToString(); 

     return excelSheets; 
    } 
    catch (Exception ex) 
    { 
     return null; 
    } 
    finally 
    { 
     // Clean up. 
     if (objConn != null) 
     { 
      objConn.Close(); 
      objConn.Dispose(); 
     } 
     if (dt != null) 
     { 
      dt.Dispose(); 
     } 
    } 
} 
+0

我猜你需要[打開XML SDK(http://www.microsoft.com/en-us/download/details.aspx?id=5124)的這種努力。這樣您可以動態訪問名稱管理器。否則,只有在您事先知道您的命名範圍的情況下,您才能從表格中獲取值。 – 2014-10-18 11:29:22

+0

@ andrei.ciprian:謝謝你的回覆。我正在離開想法,通過表名讀取命名範圍。您是否認爲可以使用Oledb或LinqToExcel包來讀取命名範圍的描述?謝謝! – Tejas 2014-10-18 17:41:50

回答

1

我是一位Open XML SDK粉絲。解決方案非常簡單。這將返回工作簿和工作表範圍的命名範圍,左邊是Excel名稱管理器定義,每張工作表有兩個帶有兩個命名範圍的工作表,右側是示例運行。

MSDN reference

enter image description here

/// <summary> 
    /// The procedure examines the workbook that you specify, 
    /// looking for the part that contains defined names. 
    /// If it exists, the procedure iterates through all the 
    /// contents of the part, adding the name and value for 
    /// each defined name to the returned dictionary 
    /// </summary> 
    public static IDictionary<String, String> XLGetDefinedNames(String fileName) 
    { 
     var returnValue = new Dictionary<String, String>(); 
     // 
     using (SpreadsheetDocument document = 
      SpreadsheetDocument.Open(fileName, false)) 
     { 
     var wbPart = document.WorkbookPart; 
     // 
     DefinedNames definedNames = wbPart.Workbook.DefinedNames; 
     if (definedNames != null) 
     { 
      foreach (DefinedName dn in definedNames) 
      returnValue.Add(dn.Name.Value, dn.Text); 
     } 
     } 
     // 
     return returnValue; 
    } 
+0

這很好。謝謝! – Tejas 2014-10-20 12:26:29

相關問題