在springboot项目中,如何进行excel表格的导入导出功能?

以下是使用 Apache POI 和 EasyExcel 实现 Excel 表格导入导出功能的具体代码示例。

1. 使用 Apache POI 实现 Excel 导入导出

添加依赖

pom.xml 中添加 Apache POI 的依赖:

XML 复制代码
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>
实体类
java 复制代码
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;

    // 构造方法、getter 和 setter 方法
    public User() {}

    public User(Long id, String name, Integer age, String email) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.email = email;
    }

    // getter 和 setter 方法省略
}
导出 Excel
java 复制代码
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

public class ExcelUtil {

    public static void exportUserList(HttpServletResponse response, List<User> userList) {
        // 创建工作簿
        Workbook workbook = new HSSFWorkbook(); // 导出 .xls 文件,使用 XSSFWorkbook 导出 .xlsx 文件
        // 创建工作表
        Sheet sheet = workbook.createSheet("用户信息表");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        String[] headers = {"ID", "姓名", "年龄", "邮箱"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 填充数据
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            Row dataRow = sheet.createRow(i + 1);
            dataRow.createCell(0).setCellValue(user.getId() == null ? "" : user.getId().toString());
            dataRow.createCell(1).setCellValue(user.getName() == null ? "" : user.getName());
            dataRow.createCell(2).setCellValue(user.getAge() == null ? "" : user.getAge().toString());
            dataRow.createCell(3).setCellValue(user.getEmail() == null ? "" : user.getEmail());
        }

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        String fileName = "用户信息表.xls"; // 文件名
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
导入 Excel
java 复制代码
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelImportUtil {

    public static List<User> importUserList(MultipartFile file) {
        List<User> userList = new ArrayList<>();

        try {
            // 获取文件流
            InputStream inputStream = file.getInputStream();
            // 创建工作簿
            Workbook workbook = WorkbookFactory.create(inputStream);
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            // 遍历行
            for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 从第 2 行(索引 1)开始读取数据
                Row row = sheet.getRow(i);
                if (row == null) continue;

                // 获取单元格数据
                Long id = getCellValue(row.getCell(0));
                String name = getCellValue(row.getCell(1));
                Integer age = getCellValue(row.getCell(2));
                String email = getCellValue(row.getCell(3));

                // 创建 User 对象并添加到列表
                User user = new User(id, name, age, email);
                userList.add(user);
            }

            workbook.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return userList;
    }

    private static Long getCellValue(Cell cell) {
        if (cell == null) return null;
        if (cell.getCellType() == CellType.NUMERIC) {
            return (long) cell.getNumericCellValue();
        } else if (cell.getCellType() == CellType.STRING) {
            return Long.parseLong(cell.getStringCellValue());
        }
        return null;
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) return null;
        if (cell.getCellType() == CellType.NUMERIC) {
            return String.valueOf((long) cell.getNumericCellValue());
        } else if (cell.getCellType() == CellType.STRING) {
            return cell.getStringCellValue();
        }
        return null;
    }
}

2. 使用 EasyExcel 实现 Excel 导入导出

添加依赖

pom.xml 中添加 EasyExcel 的依赖:

XML 复制代码
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.2.0</version>
</dependency>
实体类
java 复制代码
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.format.NumberFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;

import java.util.Date;

public class PersonVO {

    @ExcelProperty(value = "姓名", index = 0)
    private String name;

    @ExcelProperty(value = "年龄", index = 1)
    @ColumnWidth(15)
    @NumberFormat("#")
    private Integer age;

    @ExcelProperty(value = "出生日期", index = 2)
    @DateTimeFormat("yyyy-MM-dd")
    private Date birthday;

    // getter 和 setter 方法省略
}
导出 Excel
java 复制代码
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

public class ExcelExportUtil {

    public static void exportPersonList(HttpServletResponse response, List<PersonVO> personList) {
        String fileName = "人员信息表.xlsx";
        String sheetName = "人员信息表";

        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            OutputStream outputStream = response.getOutputStream();
            // 写入 Excel 文件
            EasyExcel.write(outputStream, PersonVO.class)
                    .sheet(sheetName)
                    .doWrite(personList);

            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
导入 Excel
java 复制代码
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class ExcelImportUtil {

    public static List<PersonVO> importPersonList(MultipartFile file) {
        List<PersonVO> personList = new ArrayList<>();

        try {
            EasyExcel.read(file.getInputStream(), PersonVO.class, new ReadListener<PersonVO>() {
                @Override
                public void invoke(PersonVO data, AnalysisContext analysisContext) {
                    personList.add(data);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                }
            }).sheet().doRead();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return personList;
    }
}

以上是使用 Apache POI 和 EasyExcel 实现 Excel 表格导入导出功能的具体代码示例。你可以根据实际需求选择合适的方法进行开发。

相关推荐
Victor3567 分钟前
MongoDB(72)如何创建用户和角色?
后端
Victor3569 分钟前
MongoDB(71)如何启用MongoDB身份验证?
后端
想打游戏的程序猿16 分钟前
工具与协议层——Agent 如何连接世界
后端·ai编程
希望永不加班30 分钟前
SpringBoot 过滤器(Filter)与请求链路梳理
java·spring boot·后端·spring
0xDevNull37 分钟前
Java实现Redis延迟队列:从原理到高可用架构
java·开发语言·后端
糖炒栗子032638 分钟前
Go 语言环境搭建与版本管理指南 (2026)
开发语言·后端·golang
恼书:-(空寄1 小时前
Spring 事务失效的 8 大场景 + 原因 + 解决方案
java·后端·spring
我是若尘1 小时前
我的需求代码被主干 revert 了,接下来我该怎么操作?
前端·后端·代码规范
dweizhao1 小时前
这份AI报告,把美股干崩了
后端
jiankeljx2 小时前
Java实战:Spring Boot application.yml配置文件详解
java·网络·spring boot