package cn.com.qmth.examcloud.core.questions.base.excel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collection;

/*
 * excel导出工具
 */
public class ExportUtils {
    private static final Logger log = LoggerFactory.getLogger(ExportUtils.class);
    private static final String DEFALUT_CONTENT_TYPE = "application/vnd.ms-excel";
    private static final String DEFALUT_EXT = ".xlsx";

    public static void exportEXCEL(String fileName, Class<?> dataClass, Collection<?> dataset, HttpServletResponse response) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        }

        response.setHeader("Content-Disposition", "inline; filename=" + fileName + DEFALUT_EXT);
        response.setContentType(DEFALUT_CONTENT_TYPE);

        try (ServletOutputStream outputStream = response.getOutputStream();) {
            ExcelWriter excelExporter = new ExcelWriter(dataClass);
            excelExporter.write("sheet1", dataset, outputStream);
            outputStream.flush();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}