使用C#在Excel工作表中添加下拉列表

时间:2014-09-04 07:43:31

标签: c# excel

我在整个项目中使用C#将Excel单元格填充为行和列,如下所示。现在需要在特定单元格中添加下拉列表。

var oXl = new Microsoft.Office.Interop.Excel.Application {DisplayAlerts = false};
var oWb = oXl.Workbooks.Open(excelFileName);
Microsoft.Office.Interop.Excel._Worksheet oSheet = oWb.Sheets[2];
oSheet.Cells[row, 1] = changeName + "\t";
oSheet.Cells[row, 2] = newName + "\t";
oSheet.Cells[row, 3] = (i + 1) + "\t";
oSheet.Cells[row, 4] = filename;
oSheet.Cells[row, 5] = type;
oSheet.Cells[row, 8] = dropdown; // Here I need to add a dropdown list

我该怎么做?

1 个答案:

答案 0 :(得分:8)

首先列出下拉列表

        var list = new System.Collections.Generic.List<string>();
        list.Add("Charlie");
        list.Add("Delta");
        list.Add("Echo");
        var flatList = string.Join(",", list.ToArray());

然后将此列表添加为特定单元格中的下拉列表,如下所示

var cell = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[row, 8];
            cell.Validation.Delete();
            cell.Validation.Add(
               XlDVType.xlValidateList,
               XlDVAlertStyle.xlValidAlertInformation,
               XlFormatConditionOperator.xlBetween,
               flatList,
               Type.Missing);

            cell.Validation.IgnoreBlank = true;
            cell.Validation.InCellDropdown = true;