package com.cretin.webservices.helper.excel

import com.alibaba.excel.EasyExcel
import com.alibaba.excel.support.ExcelTypeEnum
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import javax.servlet.http.HttpServletResponse

object ExcelHelper {


    /**
     * 导出excel
     */

    fun exportExcel(
        httpServletResponse: HttpServletResponse,
        fileName: String,
        sheet:String,
        header: MutableList<MutableList<String>>,
        data: MutableList<MutableList<String>>
    ) {
        setExcelResponseProp(httpServletResponse, fileName)
        EasyExcel.write(httpServletResponse.outputStream)
            .head(header)
            .excelType(ExcelTypeEnum.XLSX)
            .sheet(sheet)
            .doWrite(data)
    }

    /**
     * 设置响应结果
     *
     * @param response    响应结果对象
     * @param rawFileName 文件名
     * @throws UnsupportedEncodingException 不支持编码异常
     */
    private fun setExcelResponseProp(response: HttpServletResponse, rawFileName: String) {
        response.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        response.characterEncoding = "utf-8"
        val fileName: String = URLEncoder.encode(rawFileName, "UTF-8").replace("\\+", "%20")
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''$fileName.xlsx")
        response.setHeader("fileName",fileName+".xlsx")
    }

}

