springboot,将list集合的数据导出excel,并下载

本文介绍了一种使用Apache POI库在Spring Boot应用中,通过ClassUtil和ExcelExport2工具类将列表数据导出为Excel文件的方法,包括前端请求链接、工具类的详细实现和控制器的调用。
摘要由CSDN通过智能技术生成

springboot,将list集合的数据导出excel

这个是谷咕咕在看博客的时候一个人写的代码,这里是直接复制过来的。
非常好用,cv就可以实现工能。
在这里插入图片描述

导入依赖

<!--数据导出excel-->
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

1.前端发起请求

有人问为什么是th:href,额这个是一个模板引擎thymeleaf其实就是类似jsp。

<a th:href="@{/toexcel}" class="btn-primary" >导出全部信息</a>

2.编写工具类

ClassUtil

package com.gym.util;

import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ymgu
 * @version 1.0
 * @date 2022/2/8 17:48
 */
public final class ClassUtil {

    private ClassUtil() {
        throw new Error("工具类不允许实例化!");
    }

    /**
     * 获取类属性
     * @param targetObj 要获取属性的类
     * @return 含有类属性的集合
     */
    public static Field[] getClassAttribute(Object targetObj){

        Class<?> objectClass = targetObj.getClass();
        return objectClass.getDeclaredFields();

    }

    /**
     * 获取对象的所有get或set方法
     * @param targetObj 要获取属性的类
     * @param methodKeyword get或者set关键字
     * @return 含有类get或set方法的集合
     */
    public static List<Method> getMethod(Object targetObj,String methodKeyword){
        List<Method> methodList = new ArrayList<>();

        Class<?> objectClass = targetObj.getClass();

        Field[] field = objectClass.getDeclaredFields();
        for (int i = 0;i<field.length;i++){
            //获取属性名并组装方法名
            String fieldName = field[i].getName();
            String getMethodName = methodKeyword
                    + fieldName.substring(0, 1).toUpperCase()
                    + fieldName.substring(1);

            try {
                Method method = objectClass.getMethod(getMethodName,new Class[]{});
                methodList.add(method);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return methodList;
    }

    /**
     * 获取对象的所有get方法
     * @param targetObj 要获取属性的类
     * @return 含有类方法的集合
     */
    public static List<Method> getMethodGet(Object targetObj){
        return getMethod(targetObj,"get");
    }

    /**
     * 获取对象的所有set方法
     * @param targetObj 要获取属性的类
     * @return 含有类方法的集合
     */
    public static List<Method> getMethodSet(Object targetObj){
        return getMethod(targetObj,"set");
    }
}

ExcelExport2

package com.gym.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author ymgu
 * @version 1.0
 * @date 2022/2/8 17:48
 */
public final class ExcelExport2 {

    /**
     * 将传入的数据导出excel表并下载
     * @param response 返回的HttpServletResponse
     * @param importlist 要导出的对象的集合
     * @param attributeNames 含有每个对象属性在excel表中对应的标题字符串的数组(请按对象中属性排序调整字符串在数组中的位置)
     */
    public static void export(HttpServletResponse response, List<?> importlist, String[] attributeNames) {
        //获取数据集
        List<?> datalist = importlist;

        //声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        //生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        //设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 18);

        //获取字段名数组
        String[] tableAttributeName = attributeNames;
        //获取对象属性
        Field[] fields = ClassUtil.getClassAttribute(importlist.get(0));
        //获取对象get方法
        List<Method> methodList = ClassUtil.getMethodGet(importlist.get(0));

        //循环字段名数组,创建标题行
        Row row = sheet.createRow(0);
        for (int j = 0; j< tableAttributeName.length; j++){
            //创建列
            Cell cell = row.createCell(j);
            //设置单元类型为String
            cell.setCellType(CellType.STRING);
            cell.setCellValue(transCellType(tableAttributeName[j]));
        }
        //创建普通行
        for (int i = 0;i<datalist.size();i++){
            //因为第一行已经用于创建标题行,故从第二行开始创建
            row = sheet.createRow(i+1);
            //如果是第一行就让其为标题行
            Object targetObj = datalist.get(i);
            for (int j = 0;j<fields.length;j++){
                //创建列
                Cell cell = row.createCell(j);
                cell.setCellType(CellType.STRING);
                //
                try {
                    Object value = methodList.get(j).invoke(targetObj, new Object[]{});
                    cell.setCellValue(transCellType(value));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        response.setContentType("application/octet-stream");
        //默认Excel名称
        response.setHeader("Content-Disposition", "attachment;fileName="+"test.xls");

        try {
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static String transCellType(Object value){
        String str = null;
        if (value instanceof Date){
            Date date = (Date) value;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            str = sdf.format(date);
        }else{
            str = String.valueOf(value);
            if (str == "null"){
                str = "";
            }
        }

        return str;
    }

}

3.控制器

数据可以顺序的拿到,你只要根据数据,写好表头,创建一个数组就可以了

	/**
     *
     * **/
    @RequestMapping("/toexcel")
    public void testExprotExcel(HttpServletResponse response){
        //创建一个数组用于设置表头
        String[] arr = new String[]{"ID","学号","用户名","学院","班级","积分"};
        //调用Excel导出工具类
        ExcelExport2.export(response,activityService.getexcelinfo(),arr);
    }
SpringBoot中进行多表关联数据导入导出,可以使用easypoi这个开源库来实现。首先,你需要在项目的pom.xml文件中添加easypoi的依赖。可以通过以下方式添加依赖: ```xml <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>4.2.0</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>4.2.0</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>4.2.0</version> </dependency> ``` 在实体类中,你可以使用easypoi提供的注解来描述导出的列、集合以及关联实体。常见的注解有: - @Excel:作用在字段上,用于描述Excel的一列。 - @ExcelCollection:表示一个集合,用于描述一对多的导出情况,比如一个老师对应多个科目。 - @ExcelEntity:表示一个继续导出的实体,用于描述对象中还有导出字段的情况。 - @ExcelIgnore:表示被忽略的字段,跳过导出。 - @ExcelTarget:作用在最外层的对象上,描述对象的id,以支持针对不同导出做不同处理。 在前端的请求方法中(文件表单项),你可以使用el-upload组件来实现文件上传,并通过el-form-item来包裹。具体的代码如下所示: ```html <el-form-item> <!-- 默认name="file" --> <el-upload class="upload-demo" action="http://localhost:8080/shop/importExcel" list-type="text"> <el-button type="success">点击导入</el-button> </el-upload> </el-form-item> ``` 其中,action属性指定了文件上传的接口地址,在这个例子中是"http://localhost:8080/shop/importExcel"。 综上所述,你可以通过easypoi注解来描述导出数据列、集合和关联实体,并通过el-upload组件来实现文件上传。然后,在后端实现对应的接口来进行数据导入导出的操作。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

谷咕咕

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值