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

相关推荐
IT_陈寒1 小时前
JavaScript性能飞跃:5个V8引擎优化技巧让你的代码提速300%
前端·人工智能·后端
Victor3561 小时前
Redis(61)Redis的连接数上限是多少?
后端
Victor3561 小时前
Redis(60) Redis的复制延迟如何优化?
后端
曾令胜7 小时前
excel导出使用arthas动态追踪方法调用耗时后性能优化的过程
spring·性能优化·excel
.格子衫.7 小时前
Spring Boot 原理篇
java·spring boot·后端
多云几多7 小时前
Yudao单体项目 springboot Admin安全验证开启
java·spring boot·spring·springbootadmin
摇滚侠9 小时前
Spring Boot 3零基础教程,Spring Intializer,笔记05
spring boot·笔记·spring
Jabes.yang9 小时前
Java求职面试实战:从Spring Boot到微服务架构的技术探讨
java·数据库·spring boot·微服务·面试·消息队列·互联网大厂
兮动人10 小时前
Spring Bean耗时分析工具
java·后端·spring·bean耗时分析工具
我命由我1234510 小时前
Excel - Excel 列出一列中所有不重复数据
经验分享·学习·职场和发展·word·powerpoint·excel·职场发展