package cn.com.qmth.stmms.ms.commons.utils.excel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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


/*
 * excel导出工具
 */
public class ExportUtils {

    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 {

            response.setHeader("Content-Disposition", "inline; filename="
                    + URLEncoder.encode(fileName, "UTF-8") + DEFALUT_EXT);
            response.setContentType(DEFALUT_CONTENT_TYPE);
            ServletOutputStream outputStream = response.getOutputStream();
            ExcelWriter excelExporter = new ExcelWriter(dataClass);
            excelExporter.write("sheet1", dataset, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * excort导出
     *
     * @param fileName
     * @param wb
     * @param response
     */
    public static void exportEXCEL(String fileName, SXSSFWorkbook wb, HttpServletResponse response) {
        try {
            try {
                response.setHeader("Content-Disposition", "inline; filename="
                        + URLEncoder.encode(fileName, "UTF-8") + DEFALUT_EXT);
                response.setContentType(DEFALUT_CONTENT_TYPE);
                ServletOutputStream outputStream = response.getOutputStream();
                wb.write(outputStream);
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
