Excel-Dna C#如何从Excel工作表中的选定范围中获取值

时间:2018-08-30 12:06:10

标签: c# excel-dna

我正在尝试熟悉Excel-DNA,但是找不到有关如何在工作表单元格中选择范围内的值进行循环的文档。因此,我将拥有一个用户定义的函数,该函数将具有一些数据的单元格范围作为参数。然后,我将遍历此范围的单元格并对数据进行处理。我该如何进行这种基本操作?我在Visual Studio中的代码可能看起来像这样。

using System;
using System.Collections.Generic;
using ExcelDna.Integration;

namespace myUDF
{
    public static class Class1
    {
        [ExcelFunction(Name = "LoopArrayTester")]
        public static List<double> LoopArrayTester(??? range)
        {
            List<double> list = new List<double>();

            // loop through somehow the range in worksheet given
            // somehow in the method signature

            for(int i = 0; i < range.count; i++)
            {
                // get values of i'th cell in range and put it to list
                // or something.
            }
        }

        return list;
    }
}

1 个答案:

答案 0 :(得分:1)

最简单的方法是让您的函数将参数声明为类型object[,]。然后,您将获得一个数组,其中包含来自输​​入范围的值。您的代码可能如下所示:

public static object Concat2(object[,] values)
{
    string result = "";
    int rows = values.GetLength(0);
    int cols = values.GetLength(1);
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            object value = values[i, j];
            result += value.ToString();
        }
    }
    return result;
}

通常,您要检查值对象的类型,并根据此对象执行其他操作。从Excel-DNA传递的object [,]数组可以具有以下类型的项(取决于相应单元格中值的数据类型):

  • double
  • string
  • bool
  • ExcelDna.Integration.ExcelError
  • ExcelDna.Integration.ExcelEmpty
  • ExcelDna.Integration.ExcelMissing(如果不带参数调用该函数,则为=Concat2())。