我创建使用EXCELL文件NPOI
使用下面的代码
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
。
为实现这个任何想法将是一个很大的帮助。
尝试这个例子
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个字符的情况。
我发现这一点,并用下面的代码大大工作。
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);