OpenXml DataValidation为列设置预定义列表

我使用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);
}

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

如何为公式中的列表下拉验证添加值。 为手动添加(通过在Excel应用程序中编辑)列表值创建的XML是<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);
}
链接地址: http://www.djcxy.com/p/52349.html

上一篇: OpenXml DataValidation set predefined List for columns

下一篇: creating Excel file with OpenXML, unreadable content