Limitation while generating excel drop down list with Apache POI

后端 未结 3 1030
时光说笑
时光说笑 2020-12-02 21:54

I\'m trying to generate an excel file with some validations, I\'ve read the poi dev guides for implementing it. During implementation, I got an exception (String lite

3条回答
  •  无人及你
    2020-12-02 21:59

    The formidable solution provided by Õzbek needs only slight modification to work flawlessly with NPOI (using C# on .NET).

    Here's my code, provided as convenience for C# coders. It takes a sheet and positional elements as input and can also handle multiple dropdown, when they are arranged in columns.

    public static void CreateDropDownListForExcel(this ISheet sheet, IList dropDownValues, int startRow, int lastRow, int column) {
        if (sheet == null) {
            return;
        }
    
        //Create a hidden sheet on the workbook (using the column as an id) with the dropdown values
        IWorkbook workbook = sheet.Workbook;
        string dropDownName = sheet.SheetName + "DropDownValuesForColumn" + column;
        ISheet hiddenSheet = workbook.CreateSheet(dropDownName);
        for (int i = 0, length = dropDownValues.Count; i < length; i++) {
            string name = dropDownValues[i];
            IRow row = hiddenSheet.CreateRow(i);
            ICell cell = row.CreateCell(0);
            cell.SetCellValue(name);
        }
    
        //Create the dropdown using the fields of the hidden sheet
        IName namedCell = workbook.CreateName();
        namedCell.NameName = dropDownName;
        namedCell.RefersToFormula = (dropDownName + "!$A$1:$A$" + dropDownValues.Count);
        DVConstraint constraint = DVConstraint.CreateFormulaListConstraint(dropDownName);
        CellRangeAddressList addressList = new CellRangeAddressList(startRow, lastRow, column, column);
        HSSFDataValidation validation = new HSSFDataValidation(addressList, constraint);
        int hiddenSheetIndex = workbook.GetSheetIndex(hiddenSheet);
        workbook.SetSheetHidden(hiddenSheetIndex, SheetState.HIDDEN);
    
        //Add the Dropdown to the presenting sheet.
        sheet.AddValidationData(validation);
    }
    

提交回复
热议问题