C#Excel下拉列表

时间:2017-07-12 21:48:18

标签: c# .net excel drop-down-menu npoi

我正在尝试创建一个下拉列表,没有任何运气找到类似的示例代码或文档,所以我独自飞行

当我运行此示例代码时,我创建了

static void Main(string[] args)
    {

        using (FileStream filename = new FileStream(@"INSERTYOUROWNPATH.xlsx", FileMode.Create))
        {

            var workbook = new XSSFWorkbook();

            XSSFSheet xsheet = (XSSFSheet)workbook.CreateSheet("Validation");

            CT_DataValidation valid = new CT_DataValidation();
            valid.showDropDown = true;
            valid.allowBlank = true;

            var constraint = new XSSFDataValidationConstraint(new string[] { "0064", "0061" }); //to be used in list
            var range = new CellRangeAddressList(11, 14, 13, 13);    //apply to row 12:14 starting at column N finishing at column N
            var addingconstraint = new XSSFDataValidation(constraint, range, valid);

            addingconstraint.EmptyCellAllowed = true;
            addingconstraint.SuppressDropDownArrow = false;
            xsheet.AddValidationData(addingconstraint);

            workbook.Write(filename);

        }
    }

打开电子表格时出现以下错误:

  

“我们发现”Validations.xlsx“中的某些内容存在问题   想尽可能多地尝试恢复吗?如果您信任来源   在此工作簿中,单击是“

然后我收到以下修复信息:

  

“修复的部分:/xl/worksheets/sheet1.xml包含XML错误的部分。加载   错误。第1行第684行“

我可以了解一下失败的原因吗?

1 个答案:

答案 0 :(得分:0)

您的问题似乎与this有关数据验证和数据约束的问题非常相似。

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