我正在尝试在epplus中动态创建公式字段。如果公式字段的字符数少于255个,则可以正确创建。如果超过255个,则会抛出异常,如下所示:
异常:数据验证列表的总长度不能超过255个字符。请问有人能帮我解决这个问题吗?或者请告诉我一些替代方案。
我正在尝试在epplus中动态创建公式字段。如果公式字段的字符数少于255个,则可以正确创建。如果超过255个,则会抛出异常,如下所示:
异常:数据验证列表的总长度不能超过255个字符。请问有人能帮我解决这个问题吗?或者请告诉我一些替代方案。
问题在于您正在使用该单元格的Formula
容器来存储所有可用列表选项 - 基本上是一个CSV列表。 在Excel中,这具有255个字符的硬限制。 您可以通过在创建新的验证列表时直接在“来源”框中手动输入逗号分隔的值来查看此内容。
您最好的选择可能是在单元格中填充值,并将值的范围提供给公式。 就像这样:
using (var pack = new ExcelPackage(existingFile))
{
var ws = pack.Workbook.Worksheets.Add("Content");
//var val = ws.DataValidations.AddListValidation("A1");
//val.Formula.Values.Add("Here we have to add long text");
//val.Formula.Values.Add("All list values combined have to have more then 255 chars");
//val.Formula.Values.Add("more text 1 more text more text more text");
//val.Formula.Values.Add("more text 2 more text more text more text");
ws.Cells["B1"].Value = "Here we have to add long text";
ws.Cells["B2"].Value = "All list values combined have to have more then 255 chars";
ws.Cells["B3"].Value = "more text 1 more text more text more text";
ws.Cells["B4"].Value = "more text 2 more text more text more text";
ws.Cells["B5"].Value = "more text 2 more text more text more textmore text 2 more text more text more textmore text 2 more text more text more textmore text 2 more text more text more textmore text 2 more text more text more textmore text 2 more text more text more textmore text 2 more text more text more textmore";
var val = ws.DataValidations.AddListValidation("A1");
val.Formula.ExcelFormula = "B1:B5";
pack.SaveAs(existingFile);
}
Ernie的解决方案非常完美!除了值的范围随着每一行的变化而变化。(例如,第一行添加了B1:B5中的项目,第二行添加了B2:B6...)
以下代码更改解决了这个问题:
val.Formula.ExcelFormula = "$B$1:$B$5";