/**
 * 导出excel工具类
 *
 * @author jiyl.
 * @date 2016/3/14
 */
public class ExportExcel {

    private static Logger log = LoggerFactory.getLogger(ExportExcel.class);

    /**
     * 导出Excel文件
     *
     * @param request
     * @param response
     * @return
     */
    public String exportExcel(HttpServletRequest request, HttpServletResponse response, Map paramMap) {
        //定义action返回ajax的xml文件的字符范围及返回类型
        response.setContentType("text/xml; charset=utf-8");
        response.setHeader("Cache-Contorl", "no-cache");

        // 创建Excel的工作书册 Workbook,对应到一个excel文档
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 创建Excel的工作sheet,对应到一个excel文档的tab
        HSSFSheet sheet = workbook.createSheet(String.valueOf(paramMap.get("title")));

        // 创建字体样式
        HSSFFont font = workbook.createFont();
        font.setFontName("Verdana");
        font.setBoldweight((short) 100);
        font.setFontHeight((short) 300);

        // 创建单元格样式
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style.setFont(font);// 设置字体


        //---------需要导入的数据集----------
        List resultList = (List) paramMap.get("resultList");
        String[] fieldTitles = (String[]) paramMap.get("fieldTitles");
        String[] fields = (String[]) paramMap.get("fields");

        HSSFCell cell_1 = null;
        //写入标题
        HSSFRow row_1 = sheet.createRow(0);
        for (int i = 0; i < fieldTitles.length; i++) {
            // 设置excel每列宽度
            sheet.setColumnWidth(i, 8000);
            // 设置excel每列标题
            cell_1 = row_1.createCell(i);
            cell_1.setCellStyle(style);
            cell_1.setCellValue(fieldTitles[i]);
        }

        if (resultList != null && resultList.size() > 0) {
            for (int i = 0; i < resultList.size(); i++) {
                HSSFRow row_2 = sheet.createRow(i + 1);

                HSSFCell cell_2 = null;
                Map map = (Map) resultList.get(i);
                for (int j = 0; j < fields.length; j++) {
                    cell_2 = row_2.createCell(j);
                    cell_2.setCellValue(String.valueOf(map.get(fields[j])));
                }
            }
        }

        String currTime = DateUtils.getDate("yyyyMMddHHmmss");
        String fileName = paramMap.get("title") + currTime + ".xls";

        try {
            // 写入文件
            FileOutputStream os = new FileOutputStream("/" + "unnamed" + ".xls");
            workbook.write(os);
            os.close();

            //解决各浏览器的中文乱码问题
            String userAgent = request.getHeader("User-Agent");
            byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题
            fileName = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码

            // 将文件导出
            response.setHeader("Content-disposition", String.format("p_w_upload; filename=\"%s\"", fileName));
            response.setHeader("Content-Type", "application/octet-stream");
            OutputStream ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();

        } catch (Exception e) {
            log.error("导出Excel文件时异常:{}", e.getMessage());
            return "dbError";
        }
        return null;
    }
}