List<T>转excel下载

注解类说明

 PropertyAnno:表头名字

package com.librarymanager.akko.entity;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target(ElementType.FIELD)//规定用于全局变量
@Retention(RetentionPolicy.RUNTIME)//定义为运行时注解
/**
 * excel读取所用注解
 * @author yxm
 *
 */
public @interface PropertyAnno {
     
    String value() default "";
     
}

举例实体说明:

package com.librarymanager.akko.entity.excel;

import com.librarymanager.akko.entity.PropertyAnno;
import lombok.Data;

@Data
public class UserInfo {
    @PropertyAnno("用户姓名")
    public String userName;

    @PropertyAnno("手机号")
    public String mobile;

    @PropertyAnno("身份证ID")
    public Integer cardId;


}

util:

package com.librarymanager.akko.utils;

import com.librarymanager.akko.entity.PropertyAnno;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yxm
 * @createTime 2021/8/10 16:55
 * @explain:List<T>转成excel文件流
 */

@Component
@Slf4j
public class ObjectToExcel {

    public static <T> void ojcetToExcel(List<T> list, Class<T> targetClass, HttpServletResponse response) throws NoSuchFieldException, IllegalAccessException, IOException {
        log.info("开始下载excel");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        response.addHeader("Content-Disposition", "attachment; filename=" + "src_" + format.format(new Date()) + ".xlsx");
        //创建工作蒲
        HSSFWorkbook workbook = new HSSFWorkbook();
        //新建工作表
        HSSFSheet sheet1 = workbook.createSheet("sheet1");
        //设置工作表默认
        sheet1.setDefaultColumnWidth(20);
        //第一行
        HSSFRow row = sheet1.createRow(0);
        //设置列值
        int i = 0;
        Field[] fields = targetClass.getDeclaredFields();
        //过滤序列化ID
        List<Field> fieldList = Arrays.stream(fields).filter(field ->
                !(field.getName().equals("serialVersionUID"))).collect(Collectors.toList());
        //以属性名为第一行
        for (Field field : fieldList) {
            //字段为private时,开放权限
            boolean accessFlag = field.isAccessible();
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            String name = field.getName();
            //保持权限(安全)
            field.setAccessible(accessFlag);
            HSSFCell cell = row.createCell(i);
            //获取所有注解
            Annotation[] annotations = field.getAnnotations();
            //注解为空则继续
            if (annotations.length > 0) {
                //防止类上有多个注解
                for (Annotation annotation : annotations) {
                    //判断属性上是否存在需要注解
                    if (annotation instanceof PropertyAnno) {
                        cell.setCellValue(((PropertyAnno) annotations[0]).value());
                        continue;
                    }
                }
            } else {
                cell.setCellValue(name);
            }
            i++;
        }
        //遍历存储实体值
        for (int i1 = 0; i1 < list.size(); i1++) {
            HSSFRow row1 = sheet1.createRow(i1 + 1);
            for (int i2 = 0; i2 < fieldList.size(); i2++) {
                //创建行
                HSSFCell cell = row1.createCell(i2);
                //获取属性名
                Field declaredField = targetClass.getDeclaredField(fieldList.get(i2).getName());
                boolean accessFlag = declaredField.isAccessible();
                if (!declaredField.isAccessible()) {
                    declaredField.setAccessible(true);
                }
                //获取当前实体,当前的属性值
                String value = declaredField.get(list.get(i1)).toString();
                //设置列值
                cell.setCellValue(value);
                declaredField.setAccessible(accessFlag);
            }
        }
        ServletOutputStream outputStream = response.getOutputStream();
        //创建本地文件存储
//        FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\80550\\Desktop\\test.xlsx");
//        workbook.write(fileOutputStream);
        //放入response存储
        BufferedOutputStream bf = new BufferedOutputStream(outputStream);
        workbook.write(bf);
        workbook.close();
        bf.close();
        log.info("excel文件下载结束");
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值