We can programmatically create multiline text in a Microsoft Excel spreadsheet with Apache POI. However, it won’t be displayed as multiple lines. This is because using code to add text to a cell will not automatically adjust the cell height and apply needed formatting to turn it into multiline text.
This short tutorial will demonstrate the code needed to properly show such text.
2. Apache POI and Maven Dependency
Apache POI is an open-source library that allows a software developer to create and manipulate Microsoft Office documents. As a prerequisite, readers can refer to our article on working with Microsoft Excel in Java and a tutorial on how to insert a row in Excel using Apache POI.
To begin with, we first need to add the Apache POI dependency to our project pom.xml file:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.0</version> </dependency>
3. Adding and Formatting Multiline Text
Let’s start by having a cell with multiline text:
cell.setCellValue("Hello \n world!");
If we are to generate and save an Excel file with just the above code. It will look like bellow image:
We can click at 1 and 2 as pointed in the above image to verify that the text is indeed a multiline text.
Using code, format the cell and expand its row height to any value equal to or greater than two lines of text:
cell.getRow() .setHeightInPoints(cell.getSheet().getDefaultRowHeightInPoints() * 2);
After that, we need to set cell style to wrap the text:
CellStyle cellStyle = cell.getSheet().getWorkbook().createCellStyle(); cellStyle.setWrapText(true); cell.setCellStyle(cellStyle);
Saving a file generated with the above code and viewing it in Microsoft Excel will show multiline text in a cell.
In this tutorial, we have learned how to add multiline text to a cell using Apache POI. We then make sure that it is visible as two lines of text by applying some formatting to the cell. Otherwise, the cell will be displayed as one line.
As always, the source code for the article is available over on GitHub.