package com.jisco.dynamicweight.util;

import cn.hutool.poi.excel.ExcelWriter;
import com.jisco.dynamicweight.dynamicbasebatchdbconfig.model.DynamicBaseBatchdbConfig;
import io.swagger.annotations.ApiModelProperty;

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

public class ExcelUtil<T> {

    public static void exportExcel(HttpServletResponse response, List list, Class clazz, String title) throws IOException {
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getBigWriter();
        for (Field declaredField : clazz.getDeclaredFields()) {
            ApiModelProperty annotation = declaredField.getAnnotation(ApiModelProperty.class);
            if (annotation != null) {
                writer.addHeaderAlias(declaredField.getName(), annotation.value());
            }
        }
        writer.write(list, true);
        //out为OutputStream，需要写出到的目标流
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        String name = URLEncoder.encode(title, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭writer，释放内存
            writer.close();
            out.close();
        }
    }

}
