2

NPOI使用以下代码创建了一个 Excel 文件

            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 Validation能。whole number_specify Min and Max Value

任何实现这一目标的想法都会有很大帮助。

4

2 回答 2

2

我发现了这一点,并与以下代码一起工作。

    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);
于 2013-06-20T11:12:45.760 回答
2

试试这个例子

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 个字符的情况。

于 2017-08-28T14:10:33.370 回答