最新springboot 导出excel 工具类 (spring boot 2.5 + poi 5.0导出xlsx)

本文详细介绍了如何使用Spring Boot和Apache POI库创建一个简单的Excel导出功能,包括项目结构、代码示例(pom.xml、Controller、工具类及VO)以及实际运行效果。通过模拟数据展示了导出Excel表格的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1, 项目结构

2,完整demo

2.1, pom

2.2, controller

2.3, 导出工具类

2.4,vo

3,运行效果:


轻松搞定excel导出

1, 项目结构

2,完整demo

2.1, pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo</groupId>
    <artifactId>winding-util</artifactId>
    <version>1.0-SNAPSHOT</version>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.0.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.0.0</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

2.2, controller

package com.demo.controller;

import com.demo.util.ExcelUtil;
import com.demo.vo.UserVO;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author winding
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {


    /**
     * 导出excel
     *
     * @author winding
     */
    @RequestMapping("/export")
    public void export(HttpServletResponse response) {
        //创建模拟数据
        List<UserVO> users = mockUsers();
        //设置导出excel头
        String userExportTitle = "员工id,员工姓名,创建时间";
        //设置导出内容,注意我们全部转成String; 逗号分割; 和标题一一对应,如果空值也需要设置空值;
        List<String> userExportContents = new ArrayList<>();
        users.forEach(v -> {
            userExportContents.add(v.getId() + "," + v.getName() + "," + v.getCreateTime());
        });

        ExcelUtil.export(response, userExportTitle, userExportContents, "员工列表");
    }

    private List<UserVO> mockUsers() {
        List<UserVO> userVos = new ArrayList<>();
        userVos.add(new UserVO("张三", System.currentTimeMillis(), "2022-05-11 18:00:00"));
        userVos.add(new UserVO("张三张三", System.currentTimeMillis(), "2022-05-11 18:10:00"));
        userVos.add(new UserVO("张三张三张三", System.currentTimeMillis(), "2022-05-11 18:20:00"));
        return userVos;
    }
}

2.3, 导出工具类

package com.demo.util;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author winding
 */
public final class ExcelUtil {


    private ExcelUtil() {
    }


    /**
     * 导出 excel  xlsx
     *
     * @param response
     * @param title    标题如: "员工id,员工姓名,创建时间" (逗号分割)
     * @param values   值列表(逗号分割)
     * @param fileName 文件名字
     * @author winding
     */
    public static void export(HttpServletResponse response, String title, List<String> values, String fileName) {

        // 设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        // 设置默认文件名
        if (!StringUtils.hasLength(fileName)) {
            fileName = df.format(new Date());
        } else {
            fileName += df.format(new Date());
        }

        XSSFWorkbook workbook = new XSSFWorkbook();
        //在Workbook中,创建一个sheet,对应Excel中的工作薄(sheet)
        XSSFSheet sheet = workbook.createSheet();

        //第一行
        XSSFRow row = sheet.createRow(0);
        //第一行设置标题
        setCell(row, title);

        //设置内容
        for (int i = 0; i < values.size(); i++) {
            //从第二行开始
            XSSFRow contentRow = sheet.createRow(i + 1);
            //填充表格内容
            setCell(contentRow, values.get(i));
        }

        // 设置response头信息
        OutputStream outputStream = null;
        try {
            response.reset();
            // 改成输出excel文件
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xlsx");
            //将文件输出
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 设备行里面的单元格内容
     *
     * @param row     行
     * @param content 内容, 多个单元格以逗号分割
     */
    private static void setCell(XSSFRow row, String content) {
        // 填充表头
        String[] contents = content.split(",");
        for (int i = 0; i < contents.length; i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(contents[i]);
        }
    }
}

2.4,vo

package com.demo.vo;

public class UserVO {

    private String name;
    private Long id;
    private String createTime;

    public UserVO() {
    }


    public UserVO(String name, Long id, String time) {
        this.name = name;
        this.id = id;
        this.createTime = time;
    }

    public String getName() {
        return name;
    }

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

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
}

3,运行效果:

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

==失去

喜欢就请我喝水吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值