1. Introduction
1.绪论
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.
我们可以用Apache POI在Microsoft Excel电子表格中以编程方式创建多行文本。但是,它不会被显示为多行。这是因为使用代码将文本添加到单元格中,不会自动调整单元格的高度和应用所需的格式来将其变成多行文本。
This short tutorial will demonstrate the code needed to properly show such text.
这个简短的教程将演示正确显示此类文本所需的代码。
2. Apache POI and Maven Dependency
2.Apache POI和Maven的依赖性
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.
Apache POI是一个开源库,允许软件开发人员创建和操作Microsoft Office文档。作为前提条件,读者可以参考我们关于在Java中使用Microsoft Excel的文章以及关于如何使用Apache POI在Excel中插入一行的教程。
To begin with, we first need to add the Apache POI dependency to our project pom.xml file:
首先,我们首先需要将Apache POI依赖性添加到我们的项目pom.xml文件中。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.0</version>
</dependency>
3. Adding and Formatting Multiline Text
3.添加和格式化多行文本
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:
如果我们只用上述代码来生成和保存一个Excel文件。它将看起来像下面的图片。
We can click at 1 and 2 as pointed in the above image to verify that the text is indeed a multiline text.
我们可以点击上图中的1和2来验证该文本确实是多行文本。
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.
保存用上述代码生成的文件并在Microsoft Excel中查看,将在单元格中显示多行文本。
4. Summary
4.摘要
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.
在本教程中,我们学习了如何使用Apache POI向单元格中添加多行文本。然后,我们通过对单元格进行一些格式化处理,确保其作为两行文本可见。否则,该单元格将被显示为一行。
As always, the source code for the article is available over on GitHub.
一如既往,该文章的源代码可在GitHub上获取。