Enabling Text Wrapping in Excel Cells with Apache POI
Apache POI provides robust capabilities for manipulating Microsoft Office documents, including Excel spreadsheets. When working with Excel files programmatically, enabling automatic text wrapping within cells ensures that lengthy content remains readable without being truncated.
Implementation Approach
The key to achieving text wrapping lies in the CellStyle class. By configuring the wrapText property, cell content automatical adjusts across multiple lines when it exceeds the column width.
Complete Working Example
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelTextWrapExample {
public static void main(String[] args) {
Workbook wb = new XSSFWorkbook();
Sheet dataSheet = wb.createSheet("DataSheet");
Row dataRow = dataSheet.createRow(0);
Cell targetCell = dataRow.createCell(0);
CellStyle wrapStyle = wb.createCellStyle();
wrapStyle.setWrapText(true);
targetCell.setCellStyle(wrapStyle);
targetCell.setCellValue("This paragraph contains multiple lines of content " +
"that should automatically wrap within the cell boundaries.");
// Adjust row height to accommodate wrapped text
dataRow.setHeight((short) 600);
try (FileOutputStream fos = new FileOutputStream("output.xlsx")) {
wb.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
wb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Key Configuration Details
Row Height Adjustment: After enabling wrap text, you must manual set the row height. Without explicit height configuration, the cell displays only one line regardless of the wrap setting.
dataRow.setHeight((short) -1); // Auto-fit based on content
dataRow.setHeight((short) 600); // Fixed height in twips (1/20 of a point)
Column Width Considerations: While wrap text handles vertical overflow, you may also need to set appropriate column widths:
dataSheet.setColumnWidth(0, 5000); // Width in characters (1/256 of character width)
Architecture Overview
erDiagram
WORKBOOK {
XSSFWorkbook/xssf "Creates documents"
HSSFWorkbook/hssf "Legacy xls format"
}
WORKBOOK *-- SHEET : contains
SHEET *-- ROW : contains
ROW *-- CELL : contains
CELL *-- CELL_STYLE : applies
CELL_STYLE {
boolean wrapText
short height
short alignment
}
Common Pitfalls
- Missing row height: Omitting
setHeight()results in clipped text despitewrapTextbeing enabled - Insufficient column width: Extremely narrow columns may still truncate text visually
- Style reuse: Creating new
CellStylefor each cell impacts performance; reuse styles where appropriate
For Legacy Excel Formats (.xls)
The HSSF implementation follows identical patterns:
Workbook legacyWb = new HSSFWorkbook();
Sheet legacySheet = legacyWb.createSheet();
// Same CellStyle and wrapText configuration applies
Text wrapping functionality remains consistant across both the older HSSF (.xls) and newer XSSF (.xlsx) implementations, providing a unified API experience.