使用C#的Excel范围validation

我一直在网上看4个小时,而我却做不到。

我的目标:创build一个组合,在那里我可以对我的物品进行分类,当我点击其中一个物品时,该物品将单独出现。

在Excel中,容易做到,但是我不能在C#中完成。

我发现这个答案: 其他话题 ,但我不明白“this.Controls”从哪里来。

谢谢你的帮助

如果你想为此目的使用validation,我写下面的方法来添加一个validation和一个小的信息框,当用户单击单元格时出现:

/// <summary> /// Adds a small Infobox and a Validation with restriction (only these values will be selectable) to the specified cell. /// </summary> /// <param name="worksheet">The excel-sheet</param> /// <param name="rowNr">1-based row index of the cell that will contain the validation</param> /// <param name="columnNr">1-based column index of the cell that will contain the validation</param> /// <param name="title">Title of the Infobox</param> /// <param name="message">Message in the Infobox</param> /// <param name="validationValues">List of available values for selection of the cell. No other value, than this list is allowed to be used.</param> /// <exception cref="Exception">Thrown, if an error occurs, or the worksheet was null.</exception> public static void AddDataValidation(Worksheet worksheet, int rowNr, int columnNr, string title, string message, List<string> validationValues) { //If the message-string is too long (more than 255 characters, prune it) if (message.Length > 255) message = message.Substring(0, 254); try { //The validation requires a ';'-separated list of values, that goes as the restrictions-parameter. //Fold the list, so you can add it as restriction. (Result is "Value1;Value2;Value3") //If you use another separation-character (eg in US) change the ; appropriately (eg to the ,) string values = string.Join(";", validationValues); //Select the specified cell Range cell = worksheet.Cells[rowNr, columnNr]; //Delete any previous validation cell.Validation.Delete(); //Add the validation, that only allowes selection of provided values. cell.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, XlFormatConditionOperator.xlBetween, values, Type.Missing); cell.Validation.IgnoreBlank = true; //Optional put a message there cell.Validation.InputTitle = title; cell.Validation.InputMessage = message; } catch (Exception exception) { //This part should not be reached, but is used for stability-reasons throw new Exception(String.Format("Error when adding a Validation with restriction to the specified cell Row:{0}, Column:{1}, Message: {2}", rowNr, columnNr, message), exception); } } 

如果您不需要信息框,只需将variables标题或消息出现的部分省略即可。

我不能真正帮助你解决Excel的问题,但是this.Controls最可能来自Windows窗体应用程序。 请参阅MSDN上的这篇文章。 您可以通过创build一个空的Windows窗体应用程序然后在Form1.cs中inputthis.Controls来尝试它。

我自己发现,尝试随机的东西:

范围m_range = Sheet.get_Range(“A1”,“F9”); m_range.AutoFilter(1,Missing.Value,XlAutoFilterOperator.xlAnd,Missing.Value,true);

我真的不知道为什么,但结果是完美的,顶行用作标题,所有其他单元格被添加…酷