1. Overview
1.概述
In this tutorial, we’ll show how to merge cells in Excel with Apache POI.
在本教程中,我们将展示如何使用Apache POI在Excel中合并单元格。
2. Apache POI
2.阿帕奇POI
To begin with, we first need to add the poi dependency to our project pom.xml file:
首先,我们首先需要将poi依赖性添加到我们的项目pom.xml文件中。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.0</version>
</dependency>
Apache POI uses the Workbook interface to represent an Excel file. It also uses Sheet, Row, and Cell interfaces to model different levels of elements in an Excel file.
Apache POI使用Workbook 接口来表示一个Excel文件。它还使用Sheet、Row和Cell 接口来模拟Excel文件中不同级别的元素。
3. Merge Cells
3.合并细胞
In Excel, we sometimes want to display a string across two or more cells. For example, we can merge several cells horizontally to create a table title that spans several columns:
在Excel中,我们有时想在两个或多个单元格中显示一个字符串。例如,我们可以将几个单元格水平合并,创建一个跨越几列的表格标题。
To achieve this, we can use addMergedRegion to merge several cells defined by CellRangeAddress. There are two ways to set the cell range. Firstly, we can use four zero-based indexes to define the top-left cell location and the bottom-right cell location:
为了实现这一点,我们可以使用addMergedRegion来合并由CellRangeAddress定义的几个单元。有两种方法来设置单元格区域。首先,我们可以使用四个基于零的索引来定义左上角单元格位置和右下角单元格位置。
sheet = // existing Sheet setup
int firstRow = 0;
int lastRow = 0;
int firstCol = 0;
int lastCol = 2
sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
We can also use a cell range reference string to provide the merged region:
我们也可以使用一个单元格区域参考字符串来提供合并区域。
sheet = // existing Sheet setup
sheet.addMergedRegion(CellRangeAddress.valueOf("A1:C1"));
If cells have data before we merge them, Excel will use the top-left cell value as the merged region value. For the other cells, Excel will discard their data.
如果单元格在我们合并前有数据,Excel将使用左上角的单元格值作为合并后的区域值。对于其他单元格,Excel将舍弃其数据。
When we add multiple merged regions on an Excel file, we should not create any overlaps. Otherwise, Apache POI will throw an exception at runtime.
当我们在一个Excel文件上添加多个合并的区域时,我们不应该创建任何重叠。否则,Apache POI将在运行时抛出一个异常。
4. Summary
4.摘要
In this quick article, we showed how to merge several cells with Apache POI. We also discussed two ways to define the merged region.
在这篇快速文章中,我们展示了如何用Apache POI合并几个单元。我们还讨论了定义合并区域的两种方法。
As always, the source code for the article is available over on GitHub.
一如既往,该文章的源代码可在GitHub上获取。