在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 表格导入导出功能的具体代码示例。你可以根据实际需求选择合适的方法进行开发。

相关推荐
指令集梦境1 小时前
Cursor + Spring Boot实战:从零写一个RESTful API
spring boot·后端·restful
码云之上2 小时前
聊聊如何设计一个高效、稳定的 Node.js 接入层
前端·后端·node.js
IT_陈寒3 小时前
Vite项目build后路由404了?你可能漏了这个小配置
前端·人工智能·后端
宸津-代码粉碎机3 小时前
Spring AI企业级实战|从RAG优化到Agent多工具调度
java·大数据·人工智能·后端·python·spring
吴佳浩3 小时前
AI Infra 的真相:Go 没输,rust也不是取代
后端·rust·go
喵个咪3 小时前
实时游戏网络协议深度对比:KCP vs WebRTC vs WebSocket
后端·websocket·webrtc
普通网友3 小时前
springboot之集成Elasticsearch
spring boot·后端·elasticsearch
QuZero4 小时前
Guava Cache Deep Dive
java·后端·算法·guava
invicinble4 小时前
关于flowable流程引擎技术栈相关
spring boot
leeyi4 小时前
SSE 实时推流 —— Token 怎么一个个蹦出来
后端·agent