使用模板方法导出excel

最近在写一个导出excel时,采用了模板方法进行编写。

导出excel模板抽象类

import com.dream.biz.service.utils.DateFormatUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:导出excel,模板方法抽象类
 * @Author: liyunqiang
 * @Date: Created in 15:14 2018/5/4
 */
public abstract class ExportExcel<T> {

    protected String tableName;// 表名
    protected List<String> headList;// 表头数组
    protected List<List<Object>> datasList;// 内容集合
    protected List<Integer> widthList;// 宽度设置数组


    /**
     * 导出excel
     * @param response web的response相应
     * @param list 对象数组
     */
    public void exportExcel(HttpServletResponse response, List<T> list) {
        // 1、数据初始化
        this.init();
        // 2、设置表名
        this.setTableName();
        // 3、设置表头
        this.setHeadList();
        // 4、设置内容
        this.setDatasList(list);
        // 5、设置宽度
        this.setWidthList();
        // 6、导出
        this.exportExcel(response);
    }

    /**
     * 数据初始化
     */
    private void init() {
        tableName = "数据";
        headList = new ArrayList<String>();// 表头数组
        datasList = new ArrayList<List<Object>>();// 内容集合
        widthList = new ArrayList<Integer>();// 宽度设置数组
    }

    /**
     * 设置表名
     */
    protected abstract void setTableName();

    /**
     * 设置表头数组
     */
    protected abstract void setHeadList();

    /**
     * 设置内容数组
     */
    protected abstract void setDatasList(List<T> list);

    /**
     * 设置表格宽度
     * 钩子方法,如需修改,在子类重写方法
     */
    protected void setWidthList() {
        for (int i = 0; i < headList.size(); i++) {
            widthList.add(4000);
        }
    }

    /**
     * 生成excel文件
     */
    private void exportExcel(HttpServletResponse response) {
        // 创建一个新的Excel
        HSSFWorkbook workBook = new HSSFWorkbook();
        // 创建sheet页
        HSSFSheet sheet = workBook.createSheet();
        // 冻结第一列、第一行
        sheet.createFreezePane(1, 1);
        // sheet页名称
        workBook.setSheetName(0, tableName);
        // 创建header页
        HSSFHeader header = sheet.getHeader();
        // 设置标题居中
        header.setCenter(tableName);

        // 标题字体样式
        HSSFFont columnHeadFont = workBook.createFont();
        columnHeadFont.setFontName("宋体");
        columnHeadFont.setFontHeightInPoints((short) 10);
        columnHeadFont.setBold(true);
        // 列头的样式
        HSSFCellStyle columnHeadStyle = workBook.createCellStyle();
        columnHeadStyle.setFont(columnHeadFont);
        columnHeadStyle.setAlignment(HorizontalAlignment.CENTER);
        columnHeadStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        columnHeadStyle.setWrapText(true);
        columnHeadStyle.setBorderTop(BorderStyle.THIN);
        columnHeadStyle.setBorderBottom(BorderStyle.THIN);
        columnHeadStyle.setBorderLeft(BorderStyle.THIN);
        columnHeadStyle.setBorderRight(BorderStyle.THIN);

        // 普通单元格样式
        HSSFCellStyle style = workBook.createCellStyle();
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setWrapText(true);// 自动换行
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);

        // 设置第一行为Header
        HSSFRow row = sheet.createRow(0);
        // 添加表格
        List<HSSFCell> cellList = new ArrayList<HSSFCell>();
        HSSFCell cell;
        for (int i = 0; i < headList.size(); i++) {
            cell = row.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(columnHeadStyle);// 样式
            cellList.add(cell);
        }

        Object object = null;
        List<Object> datas;
        int len;
        if (datasList != null && !datasList.isEmpty()) {
            for (int i = 0; i < datasList.size(); i++) {
                datas = datasList.get(i);
                len = datas.size();
                row = sheet.createRow(i + 1);
                // 具体数据
                for (int j = 0; j < headList.size(); j++) {
                    cell = row.createCell(j);
                    cell.setCellStyle(style);// 样式
                    if (len > j) {// 确保不会数组越界
                        object = datas.get(j);
                        if (object != null) {
                            cell.setCellValue(object.toString());
                        }
                    }
                    cellList.add(cell);
                }
            }
        }

        // 设置表格宽度
        for (int i = 0; i < widthList.size(); i++) {
            sheet.setColumnWidth(i, widthList.get(i));
        }

        // 通过Response把数据以Excel格式保存
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((DateFormatUtil.getStringDate() + tableName + ".xls").getBytes("UTF-8"), "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workBook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


一个具体的实现类

import com.dream.biz.model.entity.ex.store.StoreVersionEx;
import com.dream.biz.service.utils.DateFormatUtil;
import com.dream.common.utils.ExportExcel;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:版本记录导出excel实现类
 * @Author: liyunqiang
 * @Date: Created in 15:23 2018/5/4
 */
@Service
@Transactional
public class StoreVersionExportExcel extends ExportExcel<StoreVersionEx> {

    private String tableTitle = "";

    public String getTableTitle() {
        return tableTitle;
    }

    public void setTableTitle(String tableTitle) {
        this.tableTitle = tableTitle;
    }

    @Override
    protected void setTableName() {
        tableName = tableTitle;
    }

    @Override
    protected void setHeadList() {
        headList.add("序号");
        headList.add("用户名");
        headList.add("设备类别");
        headList.add("系统类别");
        headList.add("软件版本号");
        headList.add("设备标识");
        headList.add("所属机构");
        headList.add("区域");
        headList.add("登录时间");
        headList.add("备注");
    }

    @Override
    protected void setDatasList(List<StoreVersionEx> list) {
        StoreVersionEx storeVersionEx;
        List<Object> datas;
        if (list != null && !list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                datas = new ArrayList<Object>();
                storeVersionEx = list.get(i);
                // 序号
                datas.add(i + 1);
                // 用户名
                datas.add(storeVersionEx.getUserName());
                // 设备类别
                datas.add(storeVersionEx.getEquipmentTypeName());
                // 系统类别
                datas.add(storeVersionEx.getSystemTypeName());
                // 软件版本号
                datas.add(storeVersionEx.getVersionCode());
                // 设备标识
                datas.add(storeVersionEx.getIdentificationCode());
                // 机构名称
                datas.add(storeVersionEx.getWarehouseCode() != null ? storeVersionEx.getWarehouseCode() + "-" + storeVersionEx.getWarehouseName() : "");
                // 区域
                datas.add(storeVersionEx.getRegionName());
                // 登录时间
                if (storeVersionEx.getCreateDate() != null) {
                    datas.add(storeVersionEx.getCreateDate() != null ? DateFormatUtil.dateToStrLong(storeVersionEx.getCreateDate()) : "");
                }
                // 备注
                datas.add(storeVersionEx.getRemark());

                // 添加到内容集合里
                datasList.add(datas);
            }
        }
    }

    @Override
    protected void setWidthList() {
        super.setWidthList();
        // 对部分列设置宽度
        widthList.set(0,2000);// 序号
        widthList.set(5,9000);// 设备标识
        widthList.set(6,6000);// 所属机构
        widthList.set(8,6000);// 登录时间
    }
}
之后又类似的excel导出需求,直接编写具体的实现类即可。

猜你喜欢

转载自blog.csdn.net/failure_lee/article/details/80317766