自动调整Apache POI中行的大小高度

我使用Apache POI将值input到电子表格中。 这些值有换行符,我可以成功地使用这个代码:

CellStyle style = cell.getCellStyle() style.setWrapText(true) cell.setCellStyle(style) 

不幸的是,虽然文本正确包装,行并不总是高度足以显示的内容。 我如何确保我的行总是正确的高度?

  HSSFWorkbook workbook=new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("FirstSheet"); HSSFRow rowhead= sheet.createRow((short)0); HSSFCellStyle style = workbook.createCellStyle(); style.setWrapText(true); row.setRowStyle(style); row.getCell(0).setCellStyle(style); 

上面的代码会生成行的dynamic高度

 currentRow.setHeight((short)-1) 

适用于XSSFCell和Excel 2013

我得到这个工作的唯一方法是编写我自己的实现来计算行高。 代码现在作为Taro项目发布,所以你可以使用它。 它有许多便利的方法,让你用less得多的代码行写一个Excel文件。

如果您希望将实现放在自己的代码中,可以在SpreadsheetTab类中find它。 有一个autoSizeRow(int rowIndex)方法的一半。 它基本上遍历行,每个单元格查找文本的行数,然后使用字体大小来计算最佳的单元格高度。 然后将行高设置为最高单元格的高度。

你不能直接调整细胞高度。 但是你可以改变行的高度

 final HSSFSheet fs = wb.createSheet("sheet1"); final HSSFRow row0 = fs.createRow(0); final HSSFCell cellA1 = row0.createCell(0); row0.setHeight((short)700); 

查看所有此链接 ,其中提供了一些代码,以根据列宽和单元格内容手动计算一行的正确高度。 我没有亲自testing过。 为便于说明,也粘贴在下面:

 // Create Font object with Font attribute (eg Font family, Font size, etc) for calculation java.awt.Font currFont = new java.awt.Font(fontName, 0, fontSize); AttributedString attrStr = new AttributedString(cellValue); attrStr.addAttribute(TextAttribute.FONT, currFont); // Use LineBreakMeasurer to count number of lines needed for the text FontRenderContext frc = new FontRenderContext(null, true, true); LineBreakMeasurer measurer = new LineBreakMeasurer(attrStr.getIterator(), frc); int nextPos = 0; int lineCnt = 0; while (measurer.getPosition() < cellValue.length()) { nextPos = measurer.nextOffset(mergedCellWidth); // mergedCellWidth is the max width of each line lineCnt++; measurer.setPosition(nextPos); } Row currRow = currSht.getRow(rowNum); currRow.setHeight((short)(currRow.getHeight() * lineCnt)); // The above solution doesn't handle the newline character, ie "\n", and only // tested under horizontal merged cells. 

对我来说aitosize工作:

 cell.getRow().setHeight((short)0); 

这里用于计算自动高度。

 short getRowHeight(Row row, String cellValue, Font font, float cellWidth) { if(cellValue.isEmpty()) return row.getHeight(); // Create Font object with Font attribute (eg Font family, Font size, etc) for calculation int style = java.awt.Font.PLAIN; if(font.getBoldweight() == Font.BOLDWEIGHT_BOLD) style = java.awt.Font.BOLD; java.awt.Font currFont = new java.awt.Font(font.getFontName(), style, font.getFontHeight()); double requiredWidth = currFont.getStringBounds(cellValue, new FontRenderContext(currFont.getTransform(), false, false)).getBounds().getWidth(); return (short) Math.ceil(font.getFontHeight() * requiredWidth / cellWidth); // The above solution doesn't handle the newline character, ie "\n", and only for row having merged cells. } 

//我们可以使用列宽的列表

 Ex: sheet.setColumnWidth(0, 2000);