在Java中进行Excel文件的读取和写入,通常使用Apache POI库。Apache POI是一个强大的Java库,用于处理Microsoft Office文档,包括Excel文件(.xls和.xlsx)。

以下是如何使用Apache POI进行Excel文件的读取和写入的详细步骤和代码示例:

1. 添加依赖

首先,你需要在你的项目中添加Apache POI的依赖。如果你使用的是Maven,可以在pom.xml文件中添加以下依赖:

<dependencies>
    <!-- Apache POI for Excel -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-collections4</artifactId>
        <version>4.4</version>
    </dependency>
</dependencies>

2. 读取Excel文件

下面是一个读取Excel文件的示例代码:

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

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

public class ExcelReader {
    public static void main(String[] args) {
        String excelFilePath = "example.xlsx"; // Excel文件路径
        try (FileInputStream fis = new FileInputStream(excelFilePath);
             Workbook workbook = new XSSFWorkbook(fis)) {

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

            // 遍历行
            for (Row row : sheet) {
                // 遍历单元格
                for (Cell cell : row) {
                    switch (cell.getCellType()) {
                        case STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case NUMERIC:
                            if (DateUtil.isCellDateFormatted(cell)) {
                                System.out.print(cell.getDateCellValue() + "\t");
                            } else {
                                System.out.print(cell.getNumericCellValue() + "\t");
                            }
                            break;
                        case BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        case FORMULA:
                            System.out.print(cell.getCellFormula() + "\t");
                            break;
                        default:
                            System.out.print("UNKNOWN\t");
                            break;
                    }
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 写入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 ExcelWriter {
    public static void main(String[] args) {
        Workbook workbook = new XSSFWorkbook(); // 创建一个新的工作簿
        Sheet sheet = workbook.createSheet("Example Sheet"); // 创建一个新的工作表

        // 创建一行并填充数据
        Row row = sheet.createRow(0);
        Cell cell1 = row.createCell(0);
        cell1.setCellValue("Hello");
        Cell cell2 = row.createCell(1);
        cell2.setCellValue("World");

        // 创建第二行并填充数据
        Row row2 = sheet.createRow(1);
        Cell cell3 = row2.createCell(0);
        cell3.setCellValue(123);
        Cell cell4 = row2.createCell(1);
        cell4.setCellValue(456.789);

        // 将工作簿写入文件
        try (FileOutputStream fos = new FileOutputStream("output.xlsx")) {
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close(); // 关闭工作簿以释放资源
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4. 运行代码

确保你已经正确配置了Maven依赖,然后编译并运行上述代码。你将会看到控制台输出读取到的Excel内容,并且生成一个名为output.xlsx的新Excel文件。

总结

通过以上步骤,你可以使用Apache POI库在Java中轻松地读取和写入Excel文件。Apache POI提供了丰富的API来处理各种Excel操作,如样式设置、公式计算等。希望这些示例对你有所帮助!

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐