如何在使用NPOI创建的Excel中为单元格设置验证

时间:2013-06-20 09:41:51

标签: c# .net excel apache-poi npoi

我使用以下代码

使用NPOI创建了一个excell文件
            var workbook = new HSSFWorkbook();
            var sheet = workbook.CreateSheet("Candidate");

            // Add header labels
            var rowIndex = 0;
            var row = sheet.CreateRow(rowIndex);
            row.CreateCell(0).SetCellValue("Name");
            row.CreateCell(1).SetCellValue("1,2,3");
            row.CreateCell(2).SetCellValue("4,5,6");
            row.CreateCell(3).SetCellValue("7,8,9");
            rowIndex++;


            // Add data rows
            for (int i = 1; i <= 5; i++)
            {
                row = sheet.CreateRow(rowIndex);
                row.CreateCell(0).SetCellValue("Candidate" + i.ToString());
                row.CreateCell(1).SetCellValue("");
                row.CreateCell(2).SetCellValue("");
                row.CreateCell(3).SetCellValue("");
                rowIndex++;
            }

我只想在每个单元格中添加一些验证。 例如:restrict cell 2 with inputs only 1,2,3

Excel we can Set Data Validationwhole number,可以specify Min and Max Value

实现这一目标的任何想法都将是一个很大的帮助。

2 个答案:

答案 0 :(得分:1)

试试这个例子

XSSFDataValidation dataValidation = null;
XSSFDataValidationConstraint dvConstraint = null;
XSSFDataValidationHelper validationHelper = null;

int DVRowLimit = (Int16.MaxValue);
XSSFCellStyle numberCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
XSSFDataFormat numberDataFormat = (XSSFDataFormat)workbook.CreateDataFormat();
numberCellStyle.SetDataFormat(numberDataFormat.GetFormat("#,###,###"));


CellRangeAddressList cellRangeFieldsType1 = new CellRangeAddressList(1, DVRowLimit, headerCount, headerCount);
dvConstraint = (XSSFDataValidationConstraint)validationHelper.CreateintConstraint(OperatorType.BETWEEN, "0", Int64.MaxValue.ToString());
dataValidation = (XSSFDataValidation)validationHelper.CreateValidation(dvConstraint, cellRangeFieldsType1);
dataValidation.ShowErrorBox = true;
dataValidation.SuppressDropDownArrow = true;
dataValidation.ErrorStyle = 0;
dataValidation.CreateErrorBox("InvalidValue", "Number Should be a integer.");
dataValidation.ShowErrorBox = true;
dataValidation.CreatePromptBox("Number Data Validation", "Enter Number.");
dataValidation.ShowPromptBox = true;
sheet.AddValidationData(dataValidation);
sheet.SetDefaultColumnStyle(column, numberCellStyle);

类似于范围验证尝试

 dvConstraint = (XSSFDataValidationConstraint)validationHelper.CreateintConstraint(OperatorType.BETWEEN, "0", "10");

我已将类似的示例合并到NPOI的文档中。它涵盖了各种类型的数据验证和约束。文档还包括约束的总字符数超过255个字符的情况。

答案 1 :(得分:0)

我发现了这一点,并使用以下代码进行了大量工作。

    var markConstraint = DVConstraint.CreateExplicitListConstraint(new string[]{"1","2","3"});
    var markColumn = new CellRangeAddressList(1, 5, 1, 1);
    var markdv = new HSSFDataValidation(markColumn, markConstraint);
    markdv.EmptyCellAllowed = true;
    markdv.CreateErrorBox("Wrong Value", "Please Enter a correct value");
    sheet.AddValidationData(markdv);