注解导出优化版(推荐,十分强大)

支持多sheet导出。支持实体类字段名称无规则排序

import com.kakaluote.demo.utils.ExcelExportUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * @Description
 * @auther 刘中华
 * @create 2019-08-24 0:32
 */
@RequestMapping("excel")
@Controller
public class ExcelController {
    //支持多sheet导出。支持实体类字段名称无规则
    @GetMapping("down")
    @ResponseBody
    public void down(HttpServletResponse response) throws Exception {
        ArrayList<Object> objects = new ArrayList<>();
        ExceptionAnalysisDetail detail = new ExceptionAnalysisDetail();
        detail.setAccount_body("名字1");detail.setAccount_body_card("卡号1");detail.setAge("22");
        objects.add(detail);

        ArrayList<Object> objects2 = new ArrayList<>();
        ExceptionAnalysisDetail detail2 = new ExceptionAnalysisDetail();
        detail2.setAccount_body("名字2");detail2.setAccount_body_card("卡号2");detail2.setAge("33");
        objects2.add(detail2);

        ExcelExportUtil excelExportUtil = new ExcelExportUtil(ExceptionAnalysisDetail.class);
        excelExportUtil.export(objects,"sheet1");
        excelExportUtil.export(objects2,"sheet2");
        excelExportUtil.down(response,"测试.xlsx");
    }
}

ExcelAttributeHandle

import java.text.SimpleDateFormat;

/**
 * @Description
 * @auther 刘中华
 * @create 2019-08-24 0:30
 */
public class ExcelAttributeHandle {

    public static final String TIME="time";
    public static final String SIGN="sign";

    public static String handle(String type, Object val){
        String format= null;
        switch (type){
            case "time":
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println(val.getClass());
                format = simpleDateFormat.format(val);
                break;
            case "sign":
                format=Integer.valueOf(val.toString())==0?"流入":"流出";
                break;
        }
        return format;
    }
}

ExcelAttribute

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @Description
 * @auther 刘中华
 * @create 2019-03-15 11:31
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelAttribute {
    /** 对应的列名称 */
    String name() default "";

    /** 列序号 */
    int sort();

    /** 字段类型对应的格式 */
    String format() default "";

}

ExceptionAnalysisDetail

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExceptionAnalysisDetail implements Serializable {
    @ExcelAttribute(name = "年龄", sort = 2)
    private String age;
    /**
     * 交易主体卡号
     */
    @ExcelAttribute(name = "交易主体卡号", sort = 1)
    private String account_body_card;
    /**
     * 交易主体
     */
    @ExcelAttribute(name = "交易主体", sort = 0)
    private String account_body;

}

ExcelExportUtil

import com.kakaluote.demo.annotion.ExcelAttribute;
import com.kakaluote.demo.excel.ExcelAttributeHandle;
import lombok.Data;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.List;

@Data
public class ExcelExportUtil<T> {

    private int rowIndex;
    private int styleIndex;
    private String templatePath;
    private Class clazz;
    private  Field fields[];
    private String[] letter = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    private XSSFWorkbook workbook;

    public ExcelExportUtil(Class clazz) {
        this.clazz = clazz;
        fields = clazz.getDeclaredFields();
        workbook =  new XSSFWorkbook();
    }

    /**
     * 基于注解导出
     */
    public void export(List<T> objs,String sheetNames) throws Exception {
        createSheet(objs,sheetNames);
    }
    private void createSheet(List<T> objs,String sheetName) throws Exception{
        XSSFSheet sheet = workbook.createSheet(sheetName);
        Row title_row = sheet.createRow(0);
        int cellIndex=0;
        for (int k = 0; k < fields.length; k++) {
            ExcelAttribute ea = fields[k].getAnnotation(ExcelAttribute.class);
            if(ea!=null) {
                int sort = ea.sort();
                Cell cell = title_row.createCell(sort);
                String name = ea.name();
                cell.setCellValue(name);
                cellIndex=sort>cellIndex?sort:cellIndex;
            }
        }
        String addStr = "A0:"+letter[cellIndex]+"0";
        //添加过滤
        CellRangeAddress addr = CellRangeAddress.valueOf(addStr);
        sheet.setAutoFilter(addr);
        //遍历塞数据
        for (int i = 0; i <objs.size() ; i++) {
            Row row = sheet.createRow(i+1);
            for (int j = 0; j <fields.length ; j++ ) {
                if(fields[j].isAnnotationPresent(ExcelAttribute.class)){
                    fields[j].setAccessible(true);
                    ExcelAttribute ea = fields[j].getAnnotation(ExcelAttribute.class);
                    Cell cell = row.createCell(ea.sort());
                    if(ea!=null&&fields[j].get(objs.get(i))!=null) {
                        if (ea.format()!=null&&!ea.format().equals("")){
                            cell.setCellValue(ExcelAttributeHandle.handle(ea.format(),fields[j].get(objs.get(i)).toString()));
                        }else{
                            cell.setCellValue(fields[j].get(objs.get(i)).toString());
                        }
                    }
                }
            }
        }
    }

    public void down(HttpServletResponse response,String fileName) throws Exception{
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("ISO8859-1")));
        response.setHeader("filename", fileName);
        workbook.write(response.getOutputStream());
    }
}
原文地址:https://www.cnblogs.com/coder-lzh/p/12426375.html