Merge Excel Cells with Apache POI Java
You can use the Apache POI library to manipulate Excel files, such as merging cells and setting content to be centered. Below is a simple example code:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class MergeCellsExample {
public static void main(String[] args) {
try (Workbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Merged Cell");
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
cell.setCellStyle(style);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
try (FileOutputStream fileOut = new FileOutputStream("workbook.xlsx")) {
workbook.write(fileOut);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we first create a new Workbook and Sheet object, then create a new Row and Cell object, and set the value of the cell to “Merged Cell”. Next, create a CellStyle object and set the horizontal and vertical alignment of the cell content to center. Then call the addMergedRegion method to merge the cells, and finally write the Workbook to a file.
This way, the operation of merging cells and setting the content centered in an Excel file was achieved.