1. 程式人生 > >POI導出excel列寬自適應

POI導出excel列寬自適應

create ren 最大 存儲 行數 als keys col wid

讓單元格寬度隨著列和單元格值的寬度自適應:

            //存儲最大列寬
            Map<Integer, Integer> maxWidth = new HashMap<>();

            // 將列頭設置到sheet的單元格中
            for (int n = 0; n < columnNum; n++) {
                HSSFCell cellRowName = rowRowName.createCell(n);                  //創建列頭對應個數的單元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //設置列頭單元格的數據類型 HSSFRichTextString text = new HSSFRichTextString(columnName[n]); cellRowName.setCellValue(text); //設置列頭單元格的值 cellRowName.setCellStyle(columnTopStyle); //
設置列頭單元格樣式 maxWidth.put(n, cellRowName.getStringCellValue().getBytes().length * 256 + 512); } sheet.createFreezePane(2, 1, 2, 1); for (int i = 0; i < dataList.size(); i++) { int j = 0; Map<String, Object> map = dataList.get(i);//
遍歷每個對象 HSSFRow row = sheet.createRow(i + 1);//創建所需的行數 for (Object key : map.keySet()) { HSSFCell cell = null; //設置單元格的數據類型 cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING); if (!"".equals(map.get(key)) && map.get(key) != null) { cell.setCellValue(map.get(key).toString()); int length = cell.getStringCellValue().getBytes().length * 256 + 512; //這裏把寬度最大限制到15000 if (length > 15000) { length = 15000; } maxWidth.put(j, Math.max(length, maxWidth.get(j))); } j++; cell.setCellStyle(style); //設置單元格樣式 } } for (int i = 0; i < columnName.length; i++) { sheet.setColumnWidth(i, maxWidth.get(i)); }

列寬隨著導出的列長自動適應:

            //讓列寬隨著導出的列長自動適應
            for (int colNum = 0; colNum < columnNum; colNum++) {
                int columnWidth = sheet.getColumnWidth(colNum) / 256;
                for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                    HSSFRow currentRow;
                    //當前行未被使用過
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    } else {
                        currentRow = sheet.getRow(rowNum);
                    }
                    if (currentRow.getCell(colNum).getRichStringCellValue() != null) {
                        //取得當前的單元格
                        HSSFCell currentCell = currentRow.getCell(colNum);
                        int length = 0;
                        //如果當前單元格類型為字符串
                        if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                            try {
                                length = currentCell.getStringCellValue().getBytes().length;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (columnWidth < length) {
                                //將單元格裏面值大小作為列寬度
                                columnWidth = length;
                            }
                        }
                    }
                }
                //再根據不同列單獨做下處理
                sheet.setColumnWidth(colNum, (columnWidth + 2) * 256);
            }

POI導出excel列寬自適應