Java POI设置表格cell内容水平垂直居中

在使用Apache POI来操作Excel文件时,有时候我们需要将表格中的内容设置为水平或垂直居中,以使Excel文件看起来更加美观和易读。本文将介绍如何使用Java POI来设置表格cell内容的水平和垂直居中。

准备工作

在开始之前,我们需要先引入Apache POI的依赖。可以在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>

接下来,我们将创建一个简单的Excel文件,并在其中添加一个表格。然后,我们将设置其中一个单元格的内容为水平垂直居中。

代码示例

首先,我们先创建一个Excel文件并添加一个表格:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelExample {
    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("Hello, World!");

            FileOutputStream fileOut = new FileOutputStream("example.xlsx");
            workbook.write(fileOut);
            fileOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上面的代码创建了一个名为example.xlsx的Excel文件,并在第一个单元格中写入了Hello, World!

接下来,我们将设置单元格内容为水平垂直居中:

// 设置单元格内容水平垂直居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cell.setCellStyle(cellStyle);

完整的代码示例如下:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelExample {
    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("Hello, World!");

            // 创建样式
            CellStyle cellStyle = workbook.createCellStyle();
            // 设置单元格内容水平垂直居中
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cell.setCellStyle(cellStyle);

            FileOutputStream fileOut = new FileOutputStream("example.xlsx");
            workbook.write(fileOut);
            fileOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

总结

通过以上代码示例,我们学习了如何使用Java POI来设置Excel表格中单元格内容的水平和垂直居中。这样可以使Excel文件更加美观和易读。希望本文对你有所帮助,谢谢阅读!

erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE-ITEM : contains
    CUSTOMER }|..| CUSTOMER : "aggregates"
    ORDER ||--|{ CUSTOMER : "invokes"
pie
    title Pie Chart
    "Apples" : 40
    "Bananas" : 30
    "Cherries" : 20
    "Dates" : 10

参考链接

  • [Apache POI官方文档](