NPOI生成下拉框

1、

HSSFSheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
CellRangeAddressList regions
= new CellRangeAddressList(0, 65535, 0, 0);
DVConstraint constraint
= DVConstraint.CreateExplicitListConstraint(new string[] { "itemA", "itemB", "itemC" });
HSSFDataValidation dataValidate
= new HSSFDataValidation(regions, constraint);
sheet1.AddValidationData(dataValidate);

 

2、

先创建一个Sheet专门用于存储下拉项的值,并将各下拉项的值写入其中:

HSSFSheet sheet2 = hssfworkbook.CreateSheet( " ShtDictionary " );
sheet2.CreateRow(
0 ).CreateCell( 0 ).SetCellValue( " itemA " );
sheet2.CreateRow(
1 ).CreateCell( 0 ).SetCellValue( " itemB " );
sheet2.CreateRow(
2 ).CreateCell( 0 ).SetCellValue( " itemC " );

然后定义一个名称,指向刚才创建的下拉项的区域:

HSSFName range = hssfworkbook.CreateName();
range.Reference
= " ShtDictionary!$A1:$A3 " ;
range.NameName
= " dicRange " ;

最后,设置数据约束时指向这个名称而不是字符数组:

HSSFSheet sheet1 = hssfworkbook.CreateSheet( " Sheet1 " );
CellRangeAddressList regions
= new CellRangeAddressList( 0 , 65535 , 0 , 0 );

DVConstraint constraint
= DVConstraint.CreateFormulaListConstraint( " dicRange " );
HSSFDataValidation dataValidate
= new HSSFDataValidation(regions, constraint);
sheet1.AddValidationData(dataValidate);

 

3、

HSSFDataValidation dataValidation = this.GetDataListValidation(result, colIndex);
sht.AddValidationData(dataValidation);

 

/**
* 设置某区域的有效性规则(列表)
* @return 生成的有效性规则
*/
private HSSFDataValidation GetDataListValidation(string[] list, int colIndex)
{
//设置数据有效性作用域
CellRangeAddressList regions = GetRegionByColIndex(colIndex);

//生成下拉框内容
DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(list);

//绑定下拉框和作用区域
HSSFDataValidation data_validation = new HSSFDataValidation(regions, constraint);
//data_validation.CreateErrorBox("输入不合法", "请输入下拉列表中的值。");
return data_validation;
}

 

//根据列序号获取整列区域
private CellRangeAddressList GetRegionByColIndex(int colIndex)
{
return new CellRangeAddressList(1, 65535, colIndex, colIndex);
}
 

你可能感兴趣的:(生成,下拉框,NPOI)