c# - 如何使用 C# Excel Interop 读取 Excel 列表元素(数据验证)?

标签 c# excel

我有一个 Excel 文件,其中的单元格已将“数据验证”设置为“列表”。因此,该单元格是一个下拉列表。如何使用 C# Excel Interop 读取此列表的元素?我可以轻松读取当前选择的值:

Range range = xlWorkSheet.UsedRange; // Worksheet
string cellValue = (range.Cells[x, y] as Excel.Range).Value2.ToString();

但我无法读取此单元格包含的下拉列表的内容。

最佳答案

正如此处所述How do I read the values of Excel dropdowns or checkboxes from c# or vb.net?没有简单的方法可以做到这一点,但可以创建自定义函数并手动执行。下面是我的函数,它将下拉值读取到字符串列表中。该函数基于之前提到的一个问题,但我添加了对其他工作表上的公式的支持。

List<string> ReadDropDownValues(Excel.Workbook xlWorkBook, Excel.Range dropDownCell)
{
    List<string> result = new List<string>();

    string formulaRange = dropDownCell.Validation.Formula1;
    string[] formulaRangeWorkSheetAndCells = formulaRange.Substring(1, formulaRange.Length - 1).Split('!');
    string[] splitFormulaRange = formulaRangeWorkSheetAndCells[1].Split(':');
    Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(formulaRangeWorkSheetAndCells[0]);

    Excel.Range valRange = (Excel.Range)xlWorkSheet.get_Range(splitFormulaRange[0], splitFormulaRange[1]);
    for (int nRows = 1; nRows <= valRange.Rows.Count; nRows++)
    {
        for (int nCols = 1; nCols <= valRange.Columns.Count; nCols++)
        {
            Excel.Range aCell = (Excel.Range)valRange.Cells[nRows, nCols];
            if (aCell.Value2 != null)
            {
                result.Add(aCell.Value2.ToString());
            }
        }
    }

    return result;
}

关于c# - 如何使用 C# Excel Interop 读取 Excel 列表元素(数据验证)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606170/

相关文章:

vba - 需要骨架代码从 PythonWin 调用 Excel VBA

vba - 如何将多列转换为单列?

python - 使用python在excel表上为我的不同数据框赋予标题

excel - 根据文件中的工作表名称从 pandas 数据框创建 csv 文件

c# - System.ArgumentException : No member matching data has been found - Unity IOC

c# - 如何使子对象知道它在其父对象上分配的属性名称?

c# - 通过反射区分类属性类型

ruby - Axlsx gem :Ruby - Creating A dropdown

c# - 在 NHibernate 中停止延迟加载或跳过加载属性?无法通过 WCF 序列化代理

c# - 将复杂数组从 Controller 传递到 View ASP.NET MVC