我有一个 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/