如何为使用 NPOI 创建的 Excel 中的单元格设置验证 [英] How to set Validation for a cell in Excel created using NPOI

查看:23
本文介绍了如何为使用 NPOI 创建的 Excel 中的单元格设置验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created an excell file using NPOI using following code

            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 input only 1,2,3

I just wanted to add some validation in each cell. For eg: restrict cell 2 with inputs only 1,2,3

Excel中,我们可以将数据验证设置为整数,并且可以指定最小值和最大值.

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

Any idea for achieving this will be a great help.

推荐答案

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

I find out this and working greatly with following code.

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

这篇关于如何为使用 NPOI 创建的 Excel 中的单元格设置验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆