package org.springblade.modules.app.utils;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Excel工具类
 *
 * @author caiyihua
 */
@Slf4j
public class ExcelUtil {

    public static void createExcelStreamByEasyExcel(HttpServletResponse response, List<? extends BaseRowModel> list,
            String fileName, String sheetName, ExcelTypeEnum type) {
        try {
            long start = System.currentTimeMillis();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + type.getValue());
            ServletOutputStream out = response.getOutputStream();
            ExcelWriter writer = new ExcelWriter(out, type);
            Sheet sheet = new Sheet(0, 0, list.get(0).getClass());
            sheet.setSheetName(sheetName);
            writer.write(list, sheet);
            writer.finish();
            out.flush();
            log.info("导出文件耗时：{}ms", System.currentTimeMillis() - start);
        } catch (Exception e) {
            log.error("导出Excel失败，异常信息：", e);
        }
    }
}
