Excel数据导出下载

package com.sysware.task.util;

import org.apache.poi.hssf.usermodel.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 导出文件工具类
 */
public class ExportFileUtil {

    /**
     * 导出统计详情EXCEL
     */
    public static void exportDetailExcel(List<Map<String, Object>> list, HttpServletResponse response) throws Exception {
        // 创建表格
        HSSFWorkbook wb = createFixationSheet(list);
        // 初始化流
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            // 表格定稿数据
            wb.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            // 设置response参数
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String("统计详情_".getBytes("GB2312"), "ISO_8859_1") + getTimeStamp() + ".xls");
            ServletOutputStream out = response.getOutputStream();
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
            if (os != null)
                os.close();
        }
    }

    /**
     * 创建EXCEL表格
     *
     * @param list
     * @throws Exception
     */
    public static HSSFWorkbook createFixationSheet(List<Map<String, Object>> list) {
        // 创建工作薄
        HSSFWorkbook wb = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = wb.createSheet("统计详情");
        HSSFRow row = sheet.createRow((short) 0);
        sheet.createFreezePane(0, 1);
        // EXCEL样式
        HSSFCellStyle cellstyle = wb.createCellStyle();
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);

        cteateCell(row, (short) 0, "任务路径", cellstyle);
        cteateCell(row, (short) 1, "名称", cellstyle);
        cteateCell(row, (short) 2, "状态", cellstyle);
        cteateCell(row, (short) 3, "完成形式", cellstyle);
        cteateCell(row, (short) 4, "责任人", cellstyle);
        cteateCell(row, (short) 5, "责任部门", cellstyle);
        cteateCell(row, (short) 6, "计划开始", cellstyle);
        cteateCell(row, (short) 7, "计划结束", cellstyle);
        cteateCell(row, (short) 8, "所属专业", cellstyle);
        cteateCell(row, (short) 9, "所属阶段", cellstyle);
        cteateCell(row, (short) 10, "创建人", cellstyle);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                if (map != null && map.size() > 0) {
                    row = sheet.createRow(i + 1);
                    cteateCell(row, (short) 0, map.get("wbsCode") + "", cellstyle);
                    cteateCell(row, (short) 1, map.get("name") + "", cellstyle);
                    cteateCell(row, (short) 2, map.get("statusName") + "", cellstyle);
                    cteateCell(row, (short) 3, map.get("completedType") + "", cellstyle);
                    cteateCell(row, (short) 4, map.get("chargeManName") + "", cellstyle);
                    cteateCell(row, (short) 5, map.get("chargeDepartmentName") + "", cellstyle);
                    cteateCell(row, (short) 6, map.get("plannedStartTime") == null ? "" : map.get("plannedStartTime") + "", cellstyle);
                    cteateCell(row, (short) 7, map.get("plannedEndTime") == null ? "" : map.get("plannedEndTime") + "", cellstyle);
                    cteateCell(row, (short) 8, map.get("discipline") + "", cellstyle);
                    cteateCell(row, (short) 9, map.get("projectPhaseName") + "", cellstyle);
                    cteateCell(row, (short) 10, map.get("creatorName") + "", cellstyle);
                }
            }
        }
        return wb;
    }


    /**
     * 方法重载,防止过度样式添加而导致的错误
     *
     * @param row       行
     * @param col       列
     * @param val       值
     * @param cellstyle 样式
     */
    private static void cteateCell(HSSFRow row, short col, String val, HSSFCellStyle cellstyle) {
        HSSFCell cell = row.createCell(col);
        cell.setCellValue(val);
        cell.setCellStyle(cellstyle);
    }

    /**
     * 创建单元格,设置表头且居中
     *
     * @param wb  工作簿
     * @param row 行
     * @param col 列
     * @param val 值
     */
    private static void cteateCell(HSSFWorkbook wb, HSSFRow row, short col, String val) {
        HSSFCell cell = row.createCell(col);
        cell.setCellValue(val);
        HSSFCellStyle cellstyle = wb.createCellStyle();
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
        cell.setCellStyle(cellstyle);
    }

    /**
     * 该方法用来产生一个时间字符串(即:时间戳)
     *
     * @return
     */
    public static String getTimeStamp() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
        Date date = new Date();
        return dateFormat.format(date);
    }
}

后端调用

/**
     * 导出统计详情数据
     *
     * @param params 查询任务详情参数集合
     */
    @RequestMapping(value = "exportDetailData/{params}", method = RequestMethod.GET)
    public void exportDetailData(@PathVariable String params, HttpServletResponse response) {
        try {
            // 解码、转Map
            Map<String, Object> queryParams = JSON.parseObject(URLDecoder.decode(params, "UTF-8"));
            // 获取任务详情数据
            List<Map<String, Object>> list = getStatisticsTaskDetailData("exportType", queryParams);
            // 导出EXCEL
            ExportFileUtil.exportDetailExcel(list, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

前端调用

// 导出任务点击事件
    $("#detailExport").bind("click", function () {
        var params = {
            "queryType": "<%=queryType%>",
            "chargeDepartmentId": "<%=chargeDepartmentId%>",
            "projectId": "<%=projectId%>",
            "statusId": "<%=statusId%>",
            "folderType": "<%=folderType%>",
            "modelId": "<%=modelId%>",
            "createDepartmentId": "<%=createDepartmentId%>",
            "creatorId": "<%=creatorId%>",
            "chargeManId": "<%=chargeManId%>",
            "planStartTime0": "<%=planStartTime0%>",
            "planStartTime1": "<%=planStartTime1%>",
            "planEndTime0": "<%=planEndTime0%>",
            "planEndTime1": "<%=planEndTime1%>",
            "actualStartTime0": "<%=actualStartTime0%>",
            "actualStartTime1": "<%=actualStartTime1%>",
            "actualEndTime0": "<%=actualEndTime0%>",
            "actualEndTime1": "<%=actualEndTime1%>"
        };
        window.location.href = basePath + "/task/businessProjectStatistics/exportDetailData/" + encodeURI(encodeURI(JSON.stringify(params)))+".action";
    });

remark

1.AJAX调用方法不会弹下载EXCEL窗口,所以选择了window.location.href调用方式
2.window.location.href调用方式在数据传输的时候会乱码,所以用了加密方法

猜你喜欢

转载自my.oschina.net/Tsher2015/blog/1825944