POI导出excel列宽自适应
让单元格宽度随着列和单元格值的宽度自适应:
//存储最大列宽 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); }