如何使用方法 List(String list, Boolean inCellDropdown) 使用 c# ClosedXML 为 Excel 中的下拉列表设置验证

How to set validation for drop down in Excel using c# ClosedXML using method List(String list, Boolean inCellDropdown)

大家好我正在尝试使用 ClosedXML 库为 excel 中的列创建下拉列表。我可以使用以下代码成功创建它。

      using (XLWorkbook wb = new XLWorkbook())
      {
        wb.Worksheets.Add(dt);
        wb.Worksheets.Add(dt2);
        var worksheet2 = wb.Worksheet(2);
        //wb.Worksheet(1).Column(11).SetDataValidation().List("one,two,three", true); This does not work fine
        wb.Worksheet(1).Column(11).SetDataValidation().List(worksheet2.Range("A2:A12"), true);// Works fine
        wb.Worksheet(1).Column(11).SetDataValidation().IgnoreBlanks = true;
        wb.Worksheet(1).Column(11).SetDataValidation().InCellDropdown = true;
        wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        wb.Style.Font.Bold = true;
        wb.SaveAs(targetFile);
      }

但我想对 SetDataValidation() 中的 List 的另一个重载方法做同样的事情,但那是创建 excel 但是当我试图打开它时,它说它已损坏。你能帮我理解为什么另一个重载方法不起作用吗?

有问题的方法是 public void List(String list, Boolean inCellDropdown). According to the Data Validation wiki page 可以使用字符串列表:

//Pass a string in this format: "Option1,Option2,Option3"
var options = new List<string>{"Option1","Option2","Option3"};
var validOptions = $"\"{String.Join(",", options)}\"";
ws.Cell(1,1).DataValidation.List(validOptions, true);

根据 Data Validation wiki 页面,列表列表必须包含双引号。

在文档示例中:

var options = new List<string>{"Option1","Option2","Option3"};
var validOptions = $"\"{String.Join(",", options)}\"";
ws.Cell(1,1).DataValidation.List(validOptions, true);

validOptions 包含:

"Option1,Option2,Option3"`

您自己的代码应更改为:

.List("\"one,two,three\"", true);

Because official document has few examples, so I post some detail examples here to show how to add dropdown list into excel.

        //set data validation, dropdown list
        // if we want list abcd in a cell, we should add ""
        var validateList = "\"A,B,C,D\"";

        //1.use column index
        worksheet.Column(3).SetDataValidation().List(validateList, true);

         //2.use column name
        worksheet.Column("D").SetDataValidation().List(validateList, true);

        //3.use column range
        worksheet.Range("E1:E20").SetDataValidation().List(validateList, true);

closedxml/wiki/Data-Validation