package com.izouma.jmrh.utils.excel;

import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.ApiModel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class ExcelUtils<T> {
    public static <T> void export(HttpServletResponse response, List<T> data) throws IOException {
        String fileName = "data.xlsx";
        if (data != null && !data.isEmpty()) {
            try {
                ApiModel apiModel = data.get(0).getClass().getAnnotation(ApiModel.class);
                fileName = URLEncoder.encode(apiModel.value() + ".xlsx", "UTF-8");
            } catch (Exception e) {
                fileName = data.get(0).getClass().getSimpleName() + ".xlsx";
            }
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        EasyExcel.write(response.getOutputStream(), data.get(0).getClass())
                .sheet("sheet")
                .registerConverter(new LocalDateConverter())
                .registerConverter(new LocalDateTimeConverter())
                .registerConverter(new BooleanConverter())
                .registerConverter(new PrimitiveBooleanConverter())
                .doWrite(data);
    }
}
