C# – 使用Oledb在Excel中获取特定工作表的NamedRanges
使用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粉丝。 解决scheme很简单。 这将返回工作簿和工作表范围的命名区域,左侧是Excel名称pipe理器定义,每个工作表有两个带有两个命名范围的工作表,右侧是示例运行。
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; }