如何使用c#Excel.Interop从Excel工作表中获取现有范围名称?

时间:2014-06-09 17:53:00

标签: c# excel office-interop

我正在使用一个包含许多命名范围的非常大的工作表。我希望将来可以修改工作表,因此我无法使用其单元格号与单元格进行交互。

如何从工作表中获取现有名称(或现有名称列表)?或者,如何告诉我的C#程序某个名称已存在并使用它?

4 个答案:

答案 0 :(得分:2)

您想要使用Excel.Worksheet.Names

foreach (Excel.Worksheet sheet in wb.Sheets) {
    foreach (Excel.Range range in sheet.Names) {
        // this is the named ranges
     }
}

Source

如果您使用EPPlus,则可以执行此操作(非常简单)

    static void Main(string[] args) {
        using (FileStream stream = new FileStream(@"C:\Users\bblack\Test\TestWorksheet.xlsx", FileMode.Append))  {
            using (ExcelPackage xl = new ExcelPackage(stream)) {
                // xl by default contains one workbook;
                bool test;
                foreach (ExcelWorksheet sheet in xl.Workbook.Worksheets) {
                    test = NamedRangeExists("NamedRange", sheet);
                }
            }
        }
    }

    static bool NamedRangeExists(string name, ExcelWorksheet ws) {
        return ws.Names.Where(n => n.Name == name).Count() > 0;
    }

这将打开指定的文件,遍历工作簿中包含的工作表,并检查其中的命名范围,名为" NamedRange"。

答案 1 :(得分:0)

你正在寻找这样的东西吗?在这个解决方案中,我把它们放在字典中

Dictionary<string, Worksheet> dictionary = new Dictionary<string, Worksheet>();
foreach ( Worksheet worksheet in ws.Worksheets )
{
   dictionary.Add( worksheet.Name, worksheet );
}

<强>更新

  

Sheet1.Range(&#34; A3:A7&#34;)&lt; - get range

wb的类型为Workbook

Dictionary<string, Range> dictionary = new Dictionary<string, Range>();
foreach (Worksheet sheet in wb.Sheets) {
    foreach (Range range in sheet.Names) {
        dictionary.Add( range.Name, Range );
        //use here range var
        var cells= range.Cells;
     }
}

参考here查看您想要的属性

答案 2 :(得分:0)

Ben Black的答案替代了我:

foreach (Excel.Worksheet sheet in wb.Sheets) {
    foreach (Excel.Name name in sheet.Names) {        
        var value = sheet.get_Range(name.NameLocal).Value;//get value of named range
        var formula = sheet.get_Range(name.NameLocal).Formula;//get Formula of named range
 }
}

答案 3 :(得分:0)

        int row = 3;

        var wb = Globals.ThisAddIn.Application.ActiveWorkbook;
        ws.Range["A6"].Value = wb.Names.Count;

        foreach (Name rangeName in wb.Names)
        {
            Range c = ws.Cells[row++, 3];
            c.Value = rangeName.NameLocal;
        }
        var ws = Globals.ThisAddIn.Application.ActiveSheet;
        ws.Range["A7"].Value = ws.Range["MyRangeName"].Value;