java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot Apache POI库读取Excel

SpringBoot使用Apache POI库读取Excel文件的操作详解

作者:Andya

在日常开发中,我们经常需要处理Excel文件中的数据,无论是从数据库导入数据、处理数据报表,还是批量生成数据,都可能会遇到需要读取和操作Excel文件的场景,本文将详细介绍如何使用Java中的Apache POI库来读取Excel文件,需要的朋友可以参考下

项目背景

假设我们需要开发一个功能,读取一个Excel文件中的数据并进行处理。通常,这样的需求会出现在以下场景中:

依赖导入

首先,你需要在项目中添加Apache POI的依赖。这里使用的是Apache POI 3.x版本,你可以在pom.xml中加入如下依赖:

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

这个依赖包包括了读取xlsx格式的支持,如果需要支持更老的xls格式,可以再加上poi模块。

读取Excel模板的实现

接下来,我们来看一个简单的示例代码,展示如何读取Excel文件的内容,并对数据进行处理。我们将以一个示例Excel表格为例,假设表格的内容如下:

姓名年龄性别
张三25
李四30
王五28

代码实现

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 读取Excel文件并进行数据处理的服务类
 */
@Service
@Slf4j
public class ReadExcelServiceImpl {

    public Boolean readExcel() {
        try {
            String pathStr = "/path/to/your/excel/file.xlsx";
            // excel文件路径
            FileInputStream fis = new FileInputStream(pathStr);
            // 创建一个工作簿对象
            Workbook workbook = new XSSFWorkbook(fis);
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            // 获取总行数
            int lastRowNum = sheet.getLastRowNum();
            
            // 存放Excel读取的数据列表
            List<ExcelDemoInfoDTO> demoInfoList = new ArrayList<>();

            // 读取数据。循环遍历行,从第二行开始,假设第一行是标题行
            for (int i = 1; i <= lastRowNum; i++) {
                log.info("Reading row {}", i);

                Row row = sheet.getRow(i);
                if (row != null) {
                    try {
                        // 获取单元格的值
                        String cell0 = getCellValue(row.getCell(0)); // 姓名
                        String cell1 = getCellValue(row.getCell(1)); // 年龄
                        String cell2 = getCellValue(row.getCell(2)); // 性别

                        // 创建数据对象并设置字段
                        ExcelDemoInfoDTO demoInfoDTO = new ExcelDemoInfoDTO();
                        demoInfoDTO.setName(cell0);
                        demoInfoDTO.setAge(Integer.parseInt(cell1));
                        demoInfoDTO.setGender(cell2);

                        // 将数据对象加入到列表
                        demoInfoList.add(demoInfoDTO);

                    } catch (Exception e) {
                        log.error("Error reading row {}", i, e);
                    }
                }
            }

            // 使用Jackson将读取的数据转换为JSON字符串
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(demoInfoList);
            System.out.println(json);

            // 关闭资源
            workbook.close();
            fis.close();

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取单元格的值,处理不同类型的单元格
     *
     * @param cell 单元格对象
     * @return 单元格的字符串值
     */
    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf((int) cell.getNumericCellValue());
            default:
                return "";
        }
    }
}

代码解析

ExcelDemoInfoDTO 数据传输对象

为了更好地封装数据,我们创建一个简单的DTO(数据传输对象)类ExcelDemoInfoDTO:

public class ExcelDemoInfoDTO {
    private String name;
    private int age;
    private String gender;

    // Getters and Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

总结

在本次实践中,我们介绍了如何使用Apache POI库在Java中读取Excel文件,获取其中的数据,并将这些数据封装为业务对象。通过这种方式,我们可以灵活地读取各种格式的Excel数据,并进行后续的业务处理。对于更复杂的Excel文件,我们还可以进一步扩展代码来处理更多类型的单元格、跨工作表读取等情况。

以上就是SpringBoot使用Apache POI库读取Excel文件的操作详解的详细内容,更多关于SpringBoot Apache POI库读取Excel的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文