gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:26:02 24 4
gpt4 key购买 nike

我在整个项目中使用 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

我该怎么做?

最佳答案

首先为下拉列表制作一个列表

        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;

关于c# - 使用C#在Excel工作表中添加下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25659888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com