poi導出excel時下拉列表值超過255問題解決方案

問題來源:spa

導出時若是下拉框中的文字總長度超過必定限制就會致使導出報255錯誤code

解決方案思路:orm

在建立sheet頁時新建一個sheet頁, 將下拉的數據寫到新建的sheet頁中, 而後將該sheet頁隱藏對象

代碼參考:blog

XSSFWorkbook wb = new XSSFWorkbook();
String sheetName = data.getName();
if (null == sheetName) {
     sheetName = "Sheet1";
}
XSSFSheet sheet = wb.createSheet(sheetName);

//獲取全部sheet頁個數
int sheetTotal = wb.getNumberOfSheets();

//處理下拉數據
if (data.getCellRangeMap() != null) {
     Set<Map.Entry<Integer, String[]>> selectSet = data.getCellRangeMap().entrySet();
     Iterator iterator = ((Set) selectSet).iterator();

     while (iterator.hasNext()) {
         Map.Entry<Integer, String[]> entryMap = (Map.Entry<Integer, String[]>) iterator.next();
         Integer columnIndex = entryMap.getKey(); //下拉框所在的列
         String[] selectList = entryMap.getValue(); //對應列下拉框數據

         //新建一個sheet頁
         String hiddenSheetName = "hiddenSheet" + sheetTotal;
         XSSFSheet hiddenSheet = wb.createSheet(hiddenSheetName);
         Row row;

         //寫入下拉數據到新的sheet頁中
         for (int i = 0; i < selectList.length; i++) {
             row = hiddenSheet.createRow(i);
             Cell cell = row.createCell(0);
             cell.setCellValue(selectList[i]);
         }

         //獲取新sheet頁內容
         String strFormula = hiddenSheetName + "!$A$1:$A$65535";
         XSSFDataValidationConstraint constraint = new XSSFDataValidationConstraint(DataValidationConstraint.ValidationType.LIST,strFormula);
         // 設置數據有效性加載在哪一個單元格上,四個參數分別是:起始行、終止行、起始列、終止列
         CellRangeAddressList regions = new CellRangeAddressList(0,65535, columnIndex, columnIndex);
         // 數據有效性對象
         DataValidationHelper help = new XSSFDataValidationHelper((XSSFSheet) sheet);
         DataValidation validation = help.createValidation(constraint, regions);
         sheet.addValidationData(validation);

         //將新建的sheet頁隱藏掉
         wb.setSheetHidden(sheetTotal, true);

         sheetTotal++;
     }
}
相關文章
相關標籤/搜索