OpenXml DataValidation 为列设置预定义列表

OpenXml DataValidation set predefined List for columns

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

DataValidation dataValidation = new DataValidation
{
    Type = DataValidationValues.List,
    AllowBlank = true,
    SequenceOfReferences = new ListValue<StringValue>() { InnerText = "B1" },
    //Formula1 = new Formula1("'SheetName'!$A:$A") // 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);
}

如果我将它与具有单元格值范围的 SheetName 一起使用,它工作正常,但如果我添加字符串,它会抛出错误 "Unreadable content found" 并删除数据验证节点。

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

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

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);
}