easypoi 复杂标题导出

1.工具类

/**
 * Copyright 2013-2015 JueYue ([email protected])
 *   
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.afterturn.easypoi.excel;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.export.ExcelBatchExportService;
import cn.afterturn.easypoi.excel.export.ExcelExportService;
import cn.afterturn.easypoi.excel.export.template.ExcelExportOfTemplateUtil;

/**
 * excel 导出工具类
 * 
 * @author JueYue
 * @version 1.0
 *  2013-10-17
 */
public final class ExcelExportUtil {

    private ExcelExportUtil() {
    }

    /**
     * @param entity
     *            表格标题属性
     * @param pojoClass
     *            Excel对象Class
     * @param dataSet
     *            Excel对象数据List
     */
    public static Workbook exportBigExcel(ExportParams entity, Class pojoClass,
                                          Collection dataSet) {
        ExcelBatchExportService batchService = ExcelBatchExportService
            .getExcelBatchExportService(entity, pojoClass);
        return batchService.appendData(dataSet);
    }

    public static Workbook exportBigExcel(ExportParams entity, List excelParams,
                                          Collection dataSet) {
        ExcelBatchExportService batchService = ExcelBatchExportService
            .getExcelBatchExportService(entity, excelParams);
        return batchService.appendData(dataSet);
    }

    public static void closeExportBigExcel() {
        ExcelBatchExportService batchService = ExcelBatchExportService.getCurrentExcelBatchExportService();
        if(batchService != null) {
            batchService.closeExportBigExcel();
        }
    }

    /**
     * @param entity
     *            表格标题属性
     * @param pojoClass
     *            Excel对象Class
     * @param dataSet
     *            Excel对象数据List
     */
    public static Workbook exportExcel(ExportParams entity, Class pojoClass,
                                       Collection dataSet) {
        Workbook workbook = getWorkbook(entity.getType(),dataSet.size());
        new ExcelExportService().createSheet(workbook, entity, pojoClass, dataSet);
        return workbook;
    }

    private static Workbook getWorkbook(ExcelType type, int size) {
        if (ExcelType.HSSF.equals(type)) {
            return new HSSFWorkbook();
        } else if (size < 100000) {
            return new XSSFWorkbook();
        } else {
            return new SXSSFWorkbook();
        }
    }

    /**
     * 根据Map创建对应的Excel
     * @param entity
     *            表格标题属性
     * @param entityList
     *            Map对象列表
     * @param dataSet
     *            Excel对象数据List
     */
    public static Workbook exportExcel(ExportParams entity, List entityList,
                                       Collection dataSet) {
        Workbook workbook = getWorkbook(entity.getType(),dataSet.size());;
        new ExcelExportService().createSheetForMap(workbook, entity, entityList, dataSet);
        return workbook;
    }

    /**
     * 一个excel 创建多个sheet
     * 
     * @param list
     *            多个Map key title 对应表格Title key entity 对应表格对应实体 key data
     *            Collection 数据
     * @return
     */
    public static Workbook exportExcel(List> list, ExcelType type) {
        Workbook workbook = getWorkbook(type,0);
        for (Map map : list) {
            ExcelExportService service = new ExcelExportService();
            service.createSheet(workbook, (ExportParams) map.get("title"),
                (Class) map.get("entity"), (Collection) map.get("data"));
        }
        return workbook;
    }

    /**
     * 导出文件通过模板解析,不推荐这个了,推荐全部通过模板来执行处理
     * 
     * @param params
     *            导出参数类
     * @param pojoClass
     *            对应实体
     * @param dataSet
     *            实体集合
     * @param map
     *            模板集合
     * @return
     */
    @Deprecated
    public static Workbook exportExcel(TemplateExportParams params, Class pojoClass,
                                       Collection dataSet, Map map) {
        return new ExcelExportOfTemplateUtil().createExcleByTemplate(params, pojoClass, dataSet,
            map);
    }

    /**
     * 导出文件通过模板解析只有模板,没有集合
     * 
     * @param params
     *            导出参数类
     * @param map
     *            模板集合
     * @return
     */
    public static Workbook exportExcel(TemplateExportParams params, Map map) {
        return new ExcelExportOfTemplateUtil().createExcleByTemplate(params, null, null, map);
    }

    /**
     * 导出文件通过模板解析只有模板,没有集合
     * 每个sheet对应一个map,导出到处,key是sheet的NUM
     * @param params
     *            导出参数类
     * @param map
     *            模板集合
     * @return
     */
    public static Workbook exportExcel(Map> map,
                                       TemplateExportParams params) {
        return new ExcelExportOfTemplateUtil().createExcleByTemplate(params, map);
    }

}

 

2 对象实体类

/**
 * Copyright 2013-2015 JueYue ([email protected])
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.afterturn.easypoi.excel.entity.params;

import java.util.List;

/**
 * excel 导出工具类,对cell类型做映射
 *
 * @author JueYue
 * @version 1.0 2013年8月24日
 */
public class ExcelExportEntity extends ExcelBaseEntity implements Comparable {


    public ExcelExportEntity() {

    }

    public ExcelExportEntity(String name) {
        super.name = name;
    }

    public ExcelExportEntity(String name, Object key) {
        super.name = name;
        this.key = key;
    }

    public ExcelExportEntity(String name, Object key, int width) {
        super.name = name;
        this.width = width;
        this.key = key;
    }

    /**
     * 如果是MAP导出,这个是map的key
     */
    private Object                  key;

    private double                  width           = 10;

    private double                  height          = 10;

    /**
     * 图片的类型,1是文件,2是数据库
     */
    private int                     exportImageType = 0;

    /**
     * 排序顺序
     */
    private int                     orderNum        = 0;

    /**
     * 是否支持换行
     */
    private boolean                 isWrap;

    /**
     * 是否需要合并
     */
    private boolean                 needMerge;
    /**
     * 单元格纵向合并
     */
    private boolean                 mergeVertical;
    /**
     * 合并依赖`
     */
    private int[]                   mergeRely;
    /**
     * 后缀
     */
    private String                  suffix;
    /**
     * 统计
     */
    private boolean                isStatistics;

    private String                  numFormat;
    /**
     *  是否隐藏列
     */
    private boolean                isColumnHidden;
    /**
     * 枚举导出属性字段
     */
    private String                  enumExportField;

    private List list;

    public int getExportImageType() {
        return exportImageType;
    }

    public double getHeight() {
        return height;
    }

    public Object getKey() {
        return key;
    }

    public List getList() {
        return list;
    }

    public int[] getMergeRely() {
        return mergeRely == null ? new int[0] : mergeRely;
    }

    public int getOrderNum() {
        return orderNum;
    }

    public double getWidth() {
        return width;
    }

    public boolean isMergeVertical() {
        return mergeVertical;
    }

    public boolean isNeedMerge() {
        return needMerge;
    }

    public boolean isWrap() {
        return isWrap;
    }

    public void setExportImageType(int exportImageType) {
        this.exportImageType = exportImageType;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public void setKey(Object key) {
        this.key = key;
    }

    public void setList(List list) {
        this.list = list;
    }

    public void setMergeRely(int[] mergeRely) {
        this.mergeRely = mergeRely;
    }

    public void setMergeVertical(boolean mergeVertical) {
        this.mergeVertical = mergeVertical;
    }

    public void setNeedMerge(boolean needMerge) {
        this.needMerge = needMerge;
    }

    public void setOrderNum(int orderNum) {
        this.orderNum = orderNum;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    public void setWrap(boolean isWrap) {
        this.isWrap = isWrap;
    }

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    public boolean isStatistics() {
        return isStatistics;
    }

    public void setStatistics(boolean isStatistics) {
        this.isStatistics = isStatistics;
    }

    public String getNumFormat() {
        return numFormat;
    }

    public void setNumFormat(String numFormat) {
        this.numFormat = numFormat;
    }

    public String getEnumExportField() {
        return enumExportField;
    }

    public void setEnumExportField(String enumExportField) {
        this.enumExportField = enumExportField;
    }

    public boolean isColumnHidden() {
        return isColumnHidden;
    }

    public void setColumnHidden(boolean columnHidden) {
        isColumnHidden = columnHidden;
    }

    @Override
    public int compareTo(ExcelExportEntity prev) {
        return this.getOrderNum() - prev.getOrderNum();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((key == null) ? 0 : key.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        ExcelExportEntity other = (ExcelExportEntity) obj;
        if (key == null) {
            if (other.key != null) {
                return false;
            }
        } else if (!key.equals(other.key)) {
            return false;
        }
        return true;
    }
}

 

3 具体方法

/**
 * 导出
 *
 * @param response
 * @param request
 * @param searchModel
 */

public void doExport(HttpServletResponse response, HttpServletRequest request,
                     StatisticsSearchModel searchModel) {
    JSONArray jsonArr = new JSONArray();
    getResultJson(searchModel, jsonArr);
    //开始拼装Excel表头
    List entity = new ArrayList();
    ExcelExportEntity excelentityNo = new ExcelExportEntity("序号", "No");
    excelentityNo.setNeedMerge(true);
    entity.add(excelentityNo);
    ExcelExportEntity excelentity = new ExcelExportEntity("姓名", "sportsmanName");
    excelentity.setNeedMerge(true);
    entity.add(excelentity);

    ExcelExportEntity excelExportEntity = new ExcelExportEntity("性别", "sex");
    excelExportEntity.setNeedMerge(true);
    entity.add(excelExportEntity);
    ExcelExportEntity excelExportEntity1 = new ExcelExportEntity("项目", "twoItemName");
    excelExportEntity1.setNeedMerge(true);
    entity.add(excelExportEntity1);
    ExcelExportEntity excelExportEntity2 = new ExcelExportEntity("注册单位", "registerName");
    excelExportEntity2.setNeedMerge(true);
    entity.add(excelExportEntity2);
    ExcelExportEntity excelExportEntity3 = new ExcelExportEntity("代表单位", "delegateName");
    excelExportEntity3.setNeedMerge(true);
    entity.add(excelExportEntity3);
    ExcelExportEntity excelExportEntity00 = new ExcelExportEntity("委托单位", "entrustUnit");
    excelExportEntity00.setNeedMerge(true);
    entity.add(excelExportEntity00);
    ExcelExportEntity excelExportEntity4 = new ExcelExportEntity("集训队/代表团", "teamName");
    excelExportEntity4.setNeedMerge(true);
    entity.add(excelExportEntity4);
    ExcelExportEntity excelExportEntity5 = new ExcelExportEntity("赛内", "outCheckNum");
    excelExportEntity5.setNeedMerge(true);
    excelExportEntity5.setStatistics(true);
    entity.add(excelExportEntity5);
    ExcelExportEntity excelExportEntity6 = new ExcelExportEntity("赛外", "inCheckNum");
    excelExportEntity6.setNeedMerge(true);
    excelExportEntity6.setStatistics(true);
    entity.add(excelExportEntity6);
    ExcelExportEntity excelExportEntity7 = new ExcelExportEntity("瓶号", "bottleNum");
    excelExportEntity7.setNeedMerge(true);
    entity.add(excelExportEntity7);
    ExcelExportEntity excelExportEntity8 = new ExcelExportEntity("检查日期", "noticeTime");
    excelExportEntity8.setNeedMerge(true);
    entity.add(excelExportEntity8);
    ExcelExportEntity excelExportEntity9 = new ExcelExportEntity("检查地点", "checkAddr");
    excelExportEntity9.setNeedMerge(true);
    entity.add(excelExportEntity9);
    ExcelExportEntity excelExportEntity10 = new ExcelExportEntity("检查类型", "checkName");
    excelExportEntity10.setNeedMerge(true);
    entity.add(excelExportEntity10);
    ExcelExportEntity excelExportEntity11 = new ExcelExportEntity("比赛名称", "checkObjName");
    excelExportEntity11.setNeedMerge(true);
    entity.add(excelExportEntity11);
    ExcelExportEntity excelExportEntity12 = new ExcelExportEntity("成绩", "scores");
    excelExportEntity12.setNeedMerge(true);
    entity.add(excelExportEntity12);
    ExcelExportEntity excelExportEntity13 = new ExcelExportEntity("重点", "keynoteName");
    excelExportEntity13.setNeedMerge(true);
    entity.add(excelExportEntity13);
    ExcelExportEntity excelExportEntity14 = new ExcelExportEntity("目标", "targetName");
    excelExportEntity14.setNeedMerge(true);
    entity.add(excelExportEntity14);

    int x = jsonArr.size();
    Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("综合查询统计", "综合查询统计"), entity, jsonArr);

    Sheet sheet = workbook.getSheetAt(0);//取此Excel文件的第一个Sheet
    Row rowEnd = sheet.getRow(sheet.getLastRowNum()); //获取到最后一个单元格
    CellStyle cellStyle = workbook.createCellStyle();
    DataFormat format = workbook.createDataFormat();
    cellStyle.setDataFormat(format.getFormat("@"));
    rowEnd.setRowStyle(cellStyle);
    for (int i = 0; i < rowEnd.getLastCellNum(); i++) {
        try {
            Cell j = rowEnd.getCell(i);
            String k = j.getStringCellValue();
            if (!StringUtils.isEmpty(k)) {
                String[] klist = k.split("\\.");
                if (klist.length >= 2) {
                    j.setCellValue(klist[0]);
                }
            }
        } catch (NullPointerException e) {
        }
    }

    //四个参数依次是:起始行,终止行,起始列,终止列
    CellRangeAddress craOne = new CellRangeAddress(x + 2, x + 2, 0, 7);//index从0开始
    sheet.addMergedRegion(craOne); //第一次合并
    downLoadExcel("综合查询统计.xls", response, request, workbook);
    LogManageUtils.recordLog("综合查询统计", "/statistics/doExportComprehensiveStatistics", "分项目检查类型数据统计",
            UserCommon.getUserId(), UserCommon.getRealName(),
            null, null, ConstantsUtils.LOG_LEVEL_INFO);

}

/**
 * 实现Excel下载
 *
 * @param fileName
 * @param response
 * @param workbook
 */
private static void downLoadExcel(String fileName, HttpServletResponse response, HttpServletRequest request, Workbook workbook) {
    try {
        String browser = "";
        browser = request.getHeader("User-Agent");
        if (-1 < browser.indexOf("MSIE 6.0") || -1 < browser.indexOf("MSIE 7.0")) {
            // IE6, IE7 浏览器
            response.addHeader("content-disposition", "attachment;filename="
                    + new String(fileName.getBytes(), "ISO8859-1"));
        } else if (-1 < browser.indexOf("MSIE 8.0")) {
            // IE8
            response.addHeader("content-disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
        } else if (-1 < browser.indexOf("MSIE 9.0")) {
            // IE9
            response.addHeader("content-disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
        } else if (-1 < browser.indexOf("Chrome")) {
            // 谷歌
            response.addHeader("content-disposition",
                    "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
        } else if (-1 < browser.indexOf("Safari")) {
            // 苹果
            response.addHeader("content-disposition", "attachment;filename="
                    + new String(fileName.getBytes(), "ISO8859-1"));
        } else {
            // 火狐或者其他的浏览器
            response.addHeader("content-disposition",
                    "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
        }
        workbook.write(response.getOutputStream());
    } catch (IOException e) {
        throw new ExcelExportException(e.getMessage());
    }
}

4 日志

package com.chinada.dms.controller.systemmgr;

import com.chinada.dms.mybatis.model.TOperationLog;
import com.chinada.dms.service.systemmgr.LogManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

@Component
public class LogManageUtils {

    private   static LogManageService logServiceStatic;

    @Autowired
    private LogManageService logManageService;
    @Autowired
    HttpServletRequest request;
    private  static  HttpServletRequest requestS;

    @PostConstruct
    public void init() {
        logServiceStatic = this.logManageService;
        requestS = request;
    }

    /**
     *
     * @param kind  模块类型
     * @param action    动作类型
     * @param message   操作信息
     * @param createUserId 创建人
     * @param crateUserName 创建人姓名
     * @param roleId    角色id
     * @param roleName 角色名称
     * @param level 日志级别(从ConstantsUtils中获取日志级别常量)
     */
    public  static  void recordLog(String kind, String action, String message, Long createUserId, String crateUserName, Long roleId, String roleName, Integer level){
        TOperationLog tOperationLog = new TOperationLog();
        tOperationLog.setKind(kind);
        tOperationLog.setAction(action);
//        tOperationLog.setBizId(0L);
        tOperationLog.setMessage(message);
        tOperationLog.setCreateUser(createUserId);
        tOperationLog.setCreateUserName(crateUserName);
        tOperationLog.setRoleId(roleId);
        tOperationLog.setRoleName(roleName);
        tOperationLog.setLevel(level);
        tOperationLog.setUpdateUser(createUserId);
        tOperationLog.setIpAddress(getIpAddr());
        Date now = new Date();
        tOperationLog.setCreateTime(now);
        tOperationLog.setUpdateTime(now );
        logServiceStatic.recordLog( tOperationLog);
    }

    /**
     * 获取本机IP地址
     * @return
     */
    public static String getLocalHost(){
        try {
            InetAddress res = InetAddress.getLocalHost();
            return res.getHostAddress();
        } catch (UnknownHostException e) {
        }
        return "UnknownHost";
    }

    /**
     * 获取用户真实IP地址,不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值
     *
     * @return ip
     */
    private static String getIpAddr() {
        String ip = requestS.getHeader("x-forwarded-for");
//        System.out.println("x-forwarded-for ip: " + ip);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值,第一个ip才是真实ip
            if( ip.indexOf(",")!=-1 ){
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = requestS.getHeader("Proxy-Client-IP");
//            System.out.println("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = requestS.getHeader("WL-Proxy-Client-IP");
//            System.out.println("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = requestS.getHeader("HTTP_CLIENT_IP");
            System.out.println("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = requestS.getHeader("HTTP_X_FORWARDED_FOR");
//            System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = requestS.getHeader("X-Real-IP");
//            System.out.println("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = requestS.getRemoteAddr();
//            System.out.println("getRemoteAddr ip: " + ip);
        }
//        System.out.println("获取客户端ip: " + ip);
        return ip;
    }
}

你可能感兴趣的:(5小功能)