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

相关推荐
电商api接口开发9 分钟前
ASP.NET MVC 入门指南三
后端·asp.net·mvc
声声codeGrandMaster9 分钟前
django之账号管理功能
数据库·后端·python·django
我的golang之路果然有问题36 分钟前
案例速成GO+redis 个人笔记
经验分享·redis·笔记·后端·学习·golang·go
嘻嘻嘻嘻嘻嘻ys1 小时前
《Vue 3.3响应式革新与TypeScript高效开发实战指南》
前端·后端
暮乘白帝过重山1 小时前
路由逻辑由 Exchange 和 Binding(绑定) 决定” 的含义
开发语言·后端·中间件·路由流程
CHQIUU1 小时前
告别手动映射:在 Spring Boot 3 中优雅集成 MapStruct
spring boot·后端·状态模式
广西千灵通网络科技有限公司1 小时前
基于Django的个性化股票交易管理系统
后端·python·django
CodeFox1 小时前
动态线程池 v1.2.1 版本发布,告警规则重构,bytebuddy 替换 cglib,新增 jmh 基准测试等!
java·后端
tonydf1 小时前
0帧起手本地跑一下BitNet
后端·ai编程
zzmgc41 小时前
常用JVM配置参数
后端