2014-10-17 81 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

相关问题