OpenXml DataValidation为列设置预定义列表

时间:2015-11-24 05:39:53

标签: c# excel openxml

我使用OpenXml创建Excel文件并导出表数据。其中一个场景是我希望列有预定义值的下拉,比如true和false。我按照this问题编写了如下代码

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

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

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

1 个答案:

答案 0 :(得分:4)

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

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