在Excel工作表中添加下拉列表

在Excel工作表中添加下拉列表

本文介绍了使用C#在Excel工作表中添加下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在整个项目中使用C#将Excel单元格填充为行和列,如下所示.现在,有一个新的要求,就是在特定的单元格中添加一个下拉列表.

I am filling the Excel cells as row and column using C# in my entire project as given below. Now there is a new requirement to add a dropdownlist in the particular cell.

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

我该怎么做?

推荐答案

首先创建一个下拉列表

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

然后将该列表作为下拉列表添加到下面的特定单元格中

then add this list as dropdown in the particular cell as below

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;

这篇关于使用C#在Excel工作表中添加下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:02