导出数据的工具类

package com.yaming.hst.utils;

import java.awt.Color;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;public abstract class BuildExcelUtils {
    private static final Logger logger = LoggerFactory.getLogger(BuildExcelUtils.class);
    List<?> items = null;
    String projectName;
    XSSFWorkbook book;
    public BuildExcelUtils(List<?> items,String projectName){
        logger.debug("[BuildExcelUtils][BuildExcelUtils]Excel导出");
        this.items = items;
        this.projectName = projectName;
    }public List<?> getItems() {
        return items;
    }
    public String getProjectName() {
        return projectName;
    }
    public XSSFWorkbook getBook() {
        return book;
    }
    /**
     * 数据转化为excel表格
     * @param excel
     * @param sheet
     * @param contentFormat
     * @param items
     */
    public abstract void buildDataTo2007Excel(ExcelWrite2007 excel,XSSFSheet sheet,XSSFCellStyle contentFormat,List<?> items,String projectName);
    
    /**
     * 导出下载excel
     * @param filename
     * @param titles
     * @param redTitleCols
     * @param colsWidth
     * @param response
     */
    public void exportExcel(String filename,String[] titles,int[] redTitleCols,int[] colsWidth,HttpServletResponse response) {
        try{
            long currTime = System.currentTimeMillis();
            String excelFileName = filename + currTime + ".xlsx";
            String sheetName = filename;
            
            logger.debug("[BuildExcelUtils][exportExcel]内存中初始化Workbook");
            ExcelWrite2007 excel = new ExcelWrite2007();
            XSSFWorkbook book = excel.createWorkbook();                
            
            logger.debug("[BuildExcelUtils][exportExcel]内存中初始化sheet");
            XSSFSheet sheet = book.createSheet(sheetName);
            
            logger.debug("[BuildExcelUtils][exportExcel]创建标题样式");
            XSSFCellStyle[] titleFormat = new  XSSFCellStyle[2];
            titleFormat[0] = getTitleFormat(excel.getWorkbook());
            titleFormat[1] = getTitleFormat2(excel.getWorkbook());
            
            logger.debug("[BuildExcelUtils][exportExcel]创建内容样式");
            XSSFCellStyle contentFormat = getContentFormat(excel.getWorkbook());
                        
            // 顶部标题
            List<String> titleList = new ArrayList<String>();
            for (int i = 0; i < titles.length; i++) {
                titleList.add(titles[i]);
            }
            logger.debug("[BuildExcelUtils][exportExcel]创建标题");
            set2007Title(excel,sheet, titleList, 0,  0, titleFormat, redTitleCols,colsWidth);
            
            
            logger.debug("[BuildExcelUtils][exportExcel]创建数据");
            buildDataTo2007Excel(excel, sheet, contentFormat,items, projectName);
            
            logger.debug("[BuildExcelUtils][exportExcel]设置列宽");
            setColWidth(sheet, excel, colsWidth);
            
            logger.debug("[BuildExcelUtils][exportExcel]设置返回response");
            responseExcel(response, excelFileName,excel.getWorkbook());
        }catch(Exception e){
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
    }
    
    public void responseExcel(HttpServletResponse response, String fileName, XSSFWorkbook xssfWorkbook) {
        OutputStream os = null;
        try{            
            logger.debug("[BuildExcelUtils][responseExcel]设置response返回信息Header");
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            os = new BufferedOutputStream(response.getOutputStream());
            logger.debug("[BuildExcelUtils][responseExcel]写入net流");
            xssfWorkbook.write(os);
        }catch(Exception e){
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }finally{
            logger.debug("[BuildExcelUtils][responseExcel]关闭net流");
            try{
            os.close();
            }catch(Exception e2){}
        }
    }
    public void set2007Title(ExcelWrite2007 excelWrite2007, XSSFSheet sheet, List<String> data, int rowIdx, int colIdx,XSSFCellStyle[] style, int[] redTitleCols,int[] colsWidth) {
        if (CheckUtils.isNullOrBlank(sheet) || CheckUtils.isNullOrBlank(data)) {
            return;
        }
        
        String val = "";
        for (int i = 0;data!=null && i < data.size(); i++) {
            val = String.valueOf(data.get(i));
            CellStyle cellStyle;
            cellStyle = style[0];
            for (int j = 0; redTitleCols!=null&&j < redTitleCols.length; j++) {
                if(i==redTitleCols[j]){
                     cellStyle = style[1];
                }
            }            
            excelWrite2007.setVal(sheet, rowIdx, colIdx + i, val, cellStyle);
        }
    }
    /**
     * EXCEL标题格式
     * @return
     * @throws WriteException
     */
    public XSSFCellStyle getTitleFormat(XSSFWorkbook book) {
        XSSFCellStyle cellStyle = book.createCellStyle();
        XSSFFont font = book.createFont();
        font.setItalic(false);
        font.setColor(HSSFColor.BLACK.index);
        font.setFontName("微软雅黑");
        font.setFontHeightInPoints((short) 10);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
        cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);
        cellStyle.setRightBorderColor(HSSFColor.BLACK.index);
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);
        cellStyle.setTopBorderColor(HSSFColor.BLACK.index);
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
        cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);
        cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        cellStyle.setFillForegroundColor(new XSSFColor(new Color(253, 233, 217)));
        cellStyle.setFillBackgroundColor(HSSFColor.WHITE.index);
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        cellStyle.setFont(font);
        cellStyle.setWrapText(true);
        return cellStyle;
    }
    //红色
    public XSSFCellStyle getTitleFormat2(XSSFWorkbook book) {
        XSSFCellStyle cellStyle = book.createCellStyle();
        XSSFFont font = book.createFont();
        font.setItalic(false);
        font.setColor(HSSFColor.BLACK.index);
        font.setFontName("微软雅黑");
        font.setFontHeightInPoints((short) 10);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
        cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);
        cellStyle.setRightBorderColor(HSSFColor.BLACK.index);
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);
        cellStyle.setTopBorderColor(HSSFColor.BLACK.index);
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
        cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);
        cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        cellStyle.setFillForegroundColor(HSSFColor.RED.index);
        cellStyle.setFillBackgroundColor(HSSFColor.GREEN.index);
        cellStyle.setAlignment(CellStyle.ALIGN_LEFT);
        cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        cellStyle.setFont(font);
        cellStyle.setWrapText(true);
        return cellStyle;
    }
    
    /**
     * 内容格式
     * @param workbook
     * @return
     */
    public XSSFCellStyle getContentFormat(XSSFWorkbook book) {
        XSSFCellStyle cellStyle = book.createCellStyle();
        XSSFFont font = book.createFont();
        font.setItalic(false);
        font.setColor(HSSFColor.BLACK.index);
        font.setFontName("微软雅黑");
        font.setFontHeightInPoints((short) 10);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
        cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);
        cellStyle.setRightBorderColor(HSSFColor.BLACK.index);
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);
        cellStyle.setTopBorderColor(HSSFColor.BLACK.index);
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
        cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);
        cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        cellStyle.setFillForegroundColor(HSSFColor.WHITE.index);
        cellStyle.setFillBackgroundColor(HSSFColor.WHITE.index);
        cellStyle.setAlignment(CellStyle.ALIGN_LEFT);
        cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        cellStyle.setFont(font);
        cellStyle.setWrapText(true);

        return cellStyle;
    }
    
    public void setColWidth(XSSFSheet sheet, ExcelWrite2007 excel, int[] colsWidth) {        
        if(colsWidth==null)return;
        for (int i = 0; i < colsWidth.length; i++) {
            if(colsWidth[i]>0){
                excel.setColumnWidth(sheet, i,colsWidth[i]);
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/inspred/p/9729187.html