使用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();
}
}
}
答案 0 :(得分:1)
我是Open XML SDK的粉丝。解决方案很简单。这将返回工作簿和工作表范围的命名范围,左侧是Excel名称管理器定义,每个工作表中有2个命名区域,右侧是样本运行。
/// <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;
}