package com.prolog.cs.biz.outbound.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.json.JSONUtil;
import com.prolog.cs.biz.outbound.model.BillSortRuleVO;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MyExcelExportUtil {

    private final static Logger log = LoggerFactory.getLogger(MyExcelExportUtil.class);

    public static void exportExcel(List<BillSortRuleVO> listData, Class<?> pojoClass, String headTitle, String sheetName, HttpServletResponse response) {
        ExportParams params = new ExportParams(headTitle,sheetName, ExcelType.HSSF);
        params.setHeight((short)8);
        OutputStream output = null;
        try {
            Workbook workbook = ExcelExportUtil.exportExcel(params,pojoClass,listData);
            String fileName = headTitle+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            // 告诉浏览器用什么软件可以打开此文件
            response.setHeader("content-Type", "application/vnd.ms-excel");
            // 下载文件的默认名称
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8") + ".xls");
            //编码
            response.setCharacterEncoding("UTF-8");
            workbook.write(response.getOutputStream());
            log.info(JSONUtil.toJsonStr(response));
            log.info("导出执行完成!");
        } catch (Exception e) {
            log.info("exportExcel失败");
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
            } catch (Exception e) {
                log.info("关闭流失败");
            }
        }
    }
}
