Interop从Excel工作表中获取现有范围名称

Interop从Excel工作表中获取现有范围名称

本文介绍了如何使用c#Excel.Interop从Excel工作表中获取现有范围名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working with a very large worksheet that has many named ranges. I expect that the worksheet will be modified in the future, so I cannot interact with cells using their cell number.

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

How can I get an existing name (or list of the existing names) from the worksheet? Alternatively, how can I tell my C# program that a certain name already exists, and to utilize it?

推荐答案

您将要使用Excel.Worksheet.Names

You'll want to use Excel.Worksheet.Names

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

来源

如果您要使用 EPPlus ,则可以这样做(非常简单)

If you were to use EPPlus, you could do this (very simple)

    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"的命名范围.

That would open up the specified file, iterate through the sheets contained in the workbook and check for a named range within them called "NamedRange".

这篇关于如何使用c#Excel.Interop从Excel工作表中获取现有范围名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 22:26