欢迎访问宙启技术站
智能推送

操作Excel表格的Java函数

发布时间:2023-07-04 00:20:17

在Java中,可以使用Apache POI库来操作Excel表格。Apache POI是一个非常流行的Java库,用于读写Microsoft Office文件,包括Excel文件。

要操作Excel表格,首先需要引入POI库的依赖。可以在Maven项目中将以下依赖添加到pom.xml文件中:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.0.1</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.0.1</version>
</dependency>

接下来,可以使用以下代码来创建一个Excel文件并写入数据:

import org.apache.poi.ss.usermodel.*;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelWriter {
    public static void main(String[] args) throws IOException {
        // 创建一个新的工作簿
        Workbook workbook = WorkbookFactory.create(true);

        // 创建一个工作表
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建一行,并在其中写入数据
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("Hello");
        cell = row.createCell(1);
        cell.setCellValue("World");

        // 将工作簿写入文件
        FileOutputStream fileOutputStream = new FileOutputStream("output.xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();

        System.out.println("Excel文件创建完成!");
    }
}

以上代码创建了一个名为"Sheet1"的工作表,并在第一行的第一列和第二列中写入了字符串"Hello"和"World"。然后将工作簿写入文件。

可以使用以下代码来读取已有的Excel文件并获取其中的数据:

import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.IOException;

public class ExcelReader {
    public static void main(String[] args) throws IOException {
        // 打开一个现有的工作簿
        FileInputStream fileInputStream = new FileInputStream("input.xlsx");
        Workbook workbook = WorkbookFactory.create(fileInputStream);

        // 获取第一个工作表
        Sheet sheet = workbook.getSheetAt(0);

        // 获取第一行的数据
        Row row = sheet.getRow(0);
        Cell cell = row.getCell(0);
        System.out.println(cell.getStringCellValue());
        cell = row.getCell(1);
        System.out.println(cell.getStringCellValue());

        fileInputStream.close();
    }
}

以上代码打开名为"input.xlsx"的Excel文件,并获取第一个工作表。然后获取第一行的数据并打印出来。

除了读取和写入数据,POI库还提供了其他一些功能,例如合并单元格、设置单元格样式、设置公式等。可以通过官方文档或其他资料了解更多关于POI库的功能和用法。

总结起来,使用Java操作Excel表格需要使用Apache POI库。通过该库的API,可以方便地创建、读取和修改Excel文件,有助于数据处理和报表生成等应用场景。