OpenXml DataValidation 为列设置预定义列表

Cha*_*ari 2 c# excel openxml

我正在使用 OpenXml 创建 Excel 文件并导出表格数据。一种情况是我希望一列具有预定义值的下拉列表,例如 true 和 false。我跟着这个问题写了如下代码

DataValidation dataValidation = new DataValidation
{
    Type = DataValidationValues.List,
    AllowBlank = true,
    SequenceOfReferences = new ListValue<StringValue>() { InnerText = "B1" },
    //Formula1 = new Formula1("'SheetName'!$A$1:$A$3") // this was used in mentioned question
    Formula1 = new Formula1("True,False") // I need predefined values.
};

DataValidations dvs = worksheet.GetFirstChild<DataValidations>(); //worksheet type => Worksheet
if (dvs != null)
{
    dvs.Count = dvs.Count + 1;
    dvs.Append(dataValidation);
}
else
{
    DataValidations newDVs = new DataValidations();
    newDVs.Append(dataValidation);
    newDVs.Count = 1;
    worksheet.Append(newDVs);
}
Run Code Online (Sandbox Code Playgroud)

如果我将它与具有单元格值范围的 SheetName 一起使用,它工作正常,但是如果我添加字符串,它会抛出错误“找到不可读的内容”并删除数据验证节点。

如何在公式本身中为列表下拉验证添加值。它为手动添加(通过在 excel 应用程序中编辑)列表值创建的 XML 是<formula1>"One,Two"</formula1>(为 excel 文件观察到的 xml)

Cha*_*ari 5

好的,我解决了这个问题。向公式添加了转义双引号并完成。

DataValidation dataValidation = new DataValidation
{
    Type = DataValidationValues.List,
    AllowBlank = true,
    SequenceOfReferences = new ListValue<StringValue>() { InnerText = "B1" },
    Formula1 = new Formula1("\"True,False\"") // escape double quotes, this is what I was missing
};

DataValidations dvs = worksheet.GetFirstChild<DataValidations>(); //worksheet type => Worksheet
if (dvs != null)
{
    dvs.Count = dvs.Count + 1;
    dvs.Append(dataValidation);
}
else
{
    DataValidations newDVs = new DataValidations();
    newDVs.Append(dataValidation);
    newDVs.Count = 1;
    worksheet.Append(newDVs);
}
Run Code Online (Sandbox Code Playgroud)