2014-09-04 87 views
2

我使用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 

我該怎麼做?

回答

6

首先作出下拉列表

 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; 
+0

它創造的下拉列表中添加此列表下拉但在下拉 – asb 2014-09-04 08:19:38

+2

沒有默認值添加默認值,如cell.Value =「默認值」; – 2014-09-04 08:31:44

+0

如果您是從其他來源引用,請至少聲明原作者:http://www.clear-lines.com/blog/post/Excel-In-Cell-DropDown-with-CSharp.aspx – 2016-11-11 14:53:09

相關問題