package com.nmgs.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.commons.io.Charsets;
import org.springframework.http.HttpHeaders;

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

public class ExcelUtil {
    /**
     * excel导出
     * @param response http响应对象
     * @param list 导出的list内容数据
     * @param clazz 导出的类型
     * @param fileNamePre 文件名（不含后缀）
     * @param sheetName sheet名
     * @throws IOException IO异常
     */
    public static void exportExcel(HttpServletResponse response, List list, Class clazz, String fileNamePre, String sheetName) throws IOException {
        // 导出时候会出现中文无法识别问题，需要转码
        //String fileName = new String(fileNamePre.getBytes(Charsets.UTF_8), Charsets.ISO_8859_1);
        String fileName = fileNamePre;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HHmmss");
        Date date = new Date();
        fileName = fileName + "_"+simpleDateFormat.format(date)+ ExcelTypeEnum.XLSX.getValue();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s", new String(URLEncoder.encode(fileName, Charsets.UTF_8.name())
                .getBytes(Charsets.UTF_8), Charsets.ISO_8859_1)));
        // 调用工具类
        EasyExcel.write(response.getOutputStream(),clazz)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(sheetName)
                .doWrite(list);
    }
}
