二次封装POI实现一行代码导出Excel

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yhflyl/article/details/88074016

引入依赖包

<!--excel导出-->
<dependency>
	 <groupId>org.apache.poi</groupId>
	 <artifactId>poi</artifactId>
	 <version>3.17</version>
</dependency>

<dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi-ooxml</artifactId>
     <version>3.17</version>
</dependency>

自定义Excel注解

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

/**
 * @author 易水●墨龙吟
 * @Description
 * @create 2019-02-25 13:18
 */
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelAttribute {

    // 字段字符码
    String name() default "";
    // 字段宽度
    int width() default 10;

    boolean sex() default false;

}

配合反射和注解实现导出主要逻辑

import com.lehui.molong.config.excel.annotation.ExcelAttribute;
import com.lehui.molong.entity.excel.ApplyInfo;
import org.apache.poi.hssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 易水●墨龙吟
 * @Description Excel导出
 * @create 2019-02-24 15:54
 */
public class ExcelUtiles {

    /**
     * Excel后缀
     */
    private final static String SUFFIX = "报名表.xls";

    /**
     * Excel导出
     * @param title
     * @param response
     * @param entityExcel
     * @param data
     */
    public static void PrintToExcel(String title, HttpServletResponse response, Class<?> entityExcel, List<ApplyInfo> data) throws UnsupportedEncodingException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        // 实例化HSSFWorkbook
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建一个Excel表单,参数为sheet的名字
        HSSFSheet sheet = workbook.createSheet("sheet");
        Map<Integer, Proprety> map = setTitle(workbook, sheet, entityExcel);
        setData(sheet, data, map);
        downloadExcel(workbook, response, setFileName(title));
    }

    /**
     * 创建文件名
     * @param title
     * @return
     */
    private static String setFileName (String title) throws UnsupportedEncodingException {
        String newFile = title + SUFFIX;
        // 防止出现文件名出现乱码
        return new String(newFile.getBytes("UTF-8"), "ISO-8859-1");
    }

    /**
     * 设置表头
     * @param workbook
     * @param sheet
     * @param entityExcel
     */
    private static Map<Integer, Proprety> setTitle(HSSFWorkbook workbook, HSSFSheet sheet, Class<?> entityExcel) {
        System.out.println("获取到:" + entityExcel.getName() + "类");
        // 定义一个map存放表头的下标和数据信息
        Map<Integer, Proprety> titleMap = new HashMap<>();
        Field[] fs = entityExcel.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            fs[i].setAccessible(true);
            // 获取属性上的注解信息
            ExcelAttribute attribute = fs[i].getAnnotation(ExcelAttribute.class);
            String name = attribute.name();
            int width = attribute.width();
            boolean sex = attribute.sex();
            System.out.println("获取到属性名称:" + name + "; 宽度:" + width);
            titleMap.put(i, new Proprety(name, width, sex));
        }
        // 创建一行
        HSSFRow row = sheet.createRow(0);
        for(int i = 0; i < titleMap.size(); i++) { sheet.setColumnWidth(i, 15 * 256); }
        // 设置样式和字体
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        HSSFCell cell;
        // 填充表头字段
        for (int j = 0; j < titleMap.size(); j++) {
            cell = row.createCell(j);
            cell.setCellStyle(style);
            cell.setCellValue(titleMap.get(j).getName());
        }
        return titleMap;
    }


    /**
     * 填数据
     * @param sheet
     * @param data
     * @param  map
     */
    private static void setData(HSSFSheet sheet, List<ApplyInfo> data, Map<Integer, Proprety> map) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
    	// 表头为第0行
        int rowNum = 1;
        for (ApplyInfo entity : data) {
        	// 反射获取实体的信息
            Class clazz = entity.getClass();
            Field[] fields = clazz.getDeclaredFields();
            HSSFRow row = sheet.createRow(rowNum);
            int index = 0;
            for(Field field : fields) {
            	// 修改权限,可以访问私有属性
                field.setAccessible(true);
                String attr = field.getName();
                // 调用方法的getXXXX 方法获取属性值
                Method method = clazz.getMethod("get" + attr.substring(0, 1).toUpperCase() + attr.substring(1));
                // 获取返回值类型
                String type = method.getAnnotatedReturnType().getType().getTypeName();
                Proprety proprety = map.get(index);
                // 判断类型,返回相应的值
                if(type.equals("java.lang.String")) {
                    row.createCell(index++).setCellValue((String)method.invoke(entity));
                } else if (type.equals("java.lang.Integer")) {
                    if(proprety.isSex()) {
                        Integer sex = (Integer)method.invoke(entity);
                        row.createCell(index++).setCellValue( sex == 1 ? "男" : "女");
                    }
                    row.createCell(index++).setCellValue((Integer)method.invoke(entity));
                }
            }
            rowNum++;
        }

    }
    
    /**
     * 浏览器下载
     * @param workbook
     * @param response
     * @param fileName
     */
    private static void downloadExcel (HSSFWorkbook workbook, HttpServletResponse response,  String fileName) {
        try {
            //清空response
            response.reset();
            //设置response的Header
            response.setHeader("Content-disposition",String.format("attachment; filename=\"%s\"", fileName));
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("UTF-8");
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            //将excel写入到输出流中
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

字段属性类

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author 易水●墨龙吟
 * @Description
 * @create 2019-02-28 21:09
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Proprety {

    private String name;

    private int width;

    private boolean sex;

}

在实体类上添加注解

import java.io.Serializable;

/**
 * @author 易水●墨龙吟
 * @Description
 * @create 2019-02-24 15:40
 */

@ToString
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
public class ApplyInfo implements Serializable {

    @ExcelAttribute(name = "申请人")
    private String applyName;

    @ExcelAttribute(name = "性别")
    private Integer applySex;

    @ExcelAttribute(name = "年龄")
    private Integer applyYear;

    @ExcelAttribute(name = "联系方式")
    private String applyPhone;

    @ExcelAttribute(name = "学校")
    private String applySchool;

    @ExcelAttribute(name = "学历")
    private String applyEducation;

    @ExcelAttribute(name = "地址")
    private String applyAddress;

    @ExcelAttribute(name = "邮箱")
    private String applyEmail;

    @ExcelAttribute(name = "工作经验")
    private String applyExperience;

    @ExcelAttribute(name = "教育经历")
    private String applyEdu;

    @ExcelAttribute(name = "职位")
    private String applySchoolDuty;

    @ExcelAttribute(name = "在荣誉")
    private String applySchoolHonor;

    @ExcelAttribute(name = "特长")
    private String applySpeciality;

}

使用

/**
 * @author 易水●墨龙吟
 * @Description
 * @create 2019-02-14 17:44
 */
@Controller
@RequestMapping("/admin")
public class JobController {
	 /**
     * 导出Excel数据表格
     * @param jobId
     */
    @GetMapping("/job/applyToExcel")
    public void printToExcel (HttpServletResponse response, @RequestParam("jobId") Integer jobId) throws UnsupportedEncodingException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    	// 获取文件名
        PartTimeJob job = partTimeJobService.selectById(jobId);
        // 获取需要导出的所有数据
        List<ApplyInfo> applyInfoData = jobApplyService.getApplyInfoAll(jobId);
        // 使用
        ExcelUtiles.PrintToExcel(job.getJobName(), response, ApplyInfo.class, applyInfoData);
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yhflyl/article/details/88074016
今日推荐