Read drop down list content from Excel using apache poi

后端 未结 2 1072
小鲜肉
小鲜肉 2020-12-10 16:34

I need to create a drop down list (Data Validation) on a particular cell in an Excel sheet and read them back.

With the help of tutorials provided by Apache PO

2条回答
  •  温柔的废话
    2020-12-10 17:17

    DataValidation is stored even in HSSF workbook, but it is in Internal Sheet of the library and since it is private so access to it is not given to application programmer. I have used Java Reflection API to access internal sheet. This code is working fine for me.

    private ArrayList init(FileInputStream fis) throws InvalidFormatException, IOException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        HSSFWorkbook hWorkbook = (HSSFWorkbook) WorkbookFactory.create(fis);
        HSSFSheet hSheet = hWorkbook.getSheetAt(1); // sheet on which you want to read data validation
        Class c = org.apache.poi.hssf.usermodel.HSSFSheet.class;
        Field field = c.getDeclaredField("_sheet");
        field.setAccessible(true);
        Object internalSheet = field.get(hSheet);
        InternalSheet is = (InternalSheet) internalSheet;
        DataValidityTable dvTable = is.getOrCreateDataValidityTable();
        Class c2 = org.apache.poi.hssf.record.aggregates.DataValidityTable.class;
        Field field2 = c2.getDeclaredField("_validationList");
        field2.setAccessible(true);
        Object records = field2.get(dvTable);
        ArrayList dvRecords = (ArrayList) records;
        return dvRecords;
    }
    

提交回复
热议问题