繁体   English   中英

C#-使用Oledb在Excel中获取特定工作表的NamedRanges

[英]C# - Get NamedRanges of a particular sheet in Excel using Oledb

使用Oledb,是否可以在Excel中获取粒子表的所有NamedRanges?

我已经编写了以下代码,该代码为我提供了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();
        }
    }
}

我是Open XML SDK迷。 解决方案很简单。 这将同时返回工作簿和工作表范围内的命名范围,左边是Excel名称管理器定义,2个工作表,每个工作表中有2个命名范围,右边是示例运行。

MSDN参考

在此处输入图片说明

    /// <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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM