package com.sky.ioc.tool;

import org.apache.coyote.Response;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.resource.HttpResource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * Excel 工具类
 * */
public class ExcelUtils {

    /**
     * 导出excel文件数据
     * @param sheetName
     * @param column
     * @param data
     * @param request
     * @param response
     */
    public static void exportExcel(String sheetName,List<String> columnName, List<String> columnKey, List<Map<String,Object>> data,
                                     HttpServletRequest request, HttpServletResponse response) {
        //创建工作薄
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        //创建sheet
        HSSFSheet sheet = hssfWorkbook.createSheet(sheetName);
        // 表头
        HSSFRow headRow = sheet.createRow(0);
        for (int i = 0; i < columnName.size(); i++){//填充表头数据
            headRow.createCell(i).setCellValue(columnName.get(i));
        }

        for (int i = 0; i < data.size(); i++) {//填充表格数据
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            for (int x = 0; x < columnKey.size(); x++) {
                dataRow.createCell(x).setCellValue(data.get(i).get(columnKey.get(x))==null?"":data.get(i).get(columnKey.get(x)).toString());
            }
        }
        response.setContentType("application/vnd.ms-excel");
        try {
            //获取浏览器名称
            String agent=request.getHeader("user-agent");
            String filename=sheetName+".xls";
            //不同浏览器需要对文件名做特殊处理
            if (agent.contains("Firefox")) { // 火狐浏览器
                Base64.Encoder encoder = Base64.getEncoder();
                filename = "=?UTF-8?B?" +
                        encoder.encodeToString(filename.getBytes("utf-8"))
                     //   + new BASE64Encoder().encode(filename.getBytes("utf-8"))
                        + "?=";
                filename = filename.replaceAll("\r\n", "");
            } else { // IE及其他浏览器
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+"," ");
            }
            //推送浏览器
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);//UTF-8
            ServletOutputStream out = response.getOutputStream();
            hssfWorkbook.write(out);
            out.close();
            hssfWorkbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
