package org.springblade.common.utils;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

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

/**
 * 导出工具类
 */
public class EasyExcelUtil {

	/**
	 *
	 * @param fileName 文件名
	 * @param response
	 * @param pojoClass 对象
	 * @param list 数据
	 * @throws IOException
	 */
    public static void downLoadExcel( HttpServletResponse response,String fileName, Class<?> pojoClass,List<?> list) throws IOException {
        try {
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8"));
			response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
			ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), pojoClass).build();
			WriteSheet writeSheet = EasyExcel.writerSheet().build();
			excelWriter.write(list, writeSheet);
			excelWriter.finish();
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }


    /**
     * Excel 类型枚举
     */
    enum ExcelTypeEnum {
        XLS("xls"), XLSX("xlsx");
        private String value;

        ExcelTypeEnum(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }


}
