1. 程式人生 > >list集合對象以excel導出

list集合對象以excel導出

ride utils lang nor app tor erro let point

一:模板

  

package  com.hailian.util;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author WangXuzheng *
*/ public abstract class SettlrExcelExportTemplate<T> implements ExcelExportTemplate<T> { Logger logger=LoggerFactory.getLogger(SettlrExcelExportTemplate.class); /** * 默認表格寬度 */ private static final int DEFAULT_COLUMN_WIDTH = 5000; /** * excel文件對象 */ protected Workbook workbook; /** * excel sheet列表 */ protected List<Sheet> sheets = new ArrayList<Sheet>(); /** * 標題欄 */ protected String[][] titles; protected CellStyle captionRowSytle; /** * 默認標題行樣式 */ protected CellStyle titleRowStyle; /** * 默認內容行樣式 */ protected CellStyle bodyRowStyle; /** * 各個sheet是否包含擡頭,key:sheet坐標,value:包含true,否則false */ protected Map<Integer, Boolean> hasCaptionMap = new HashMap<Integer, Boolean>(); /** * 默認單元格寬度 */ protected int columnWidth = DEFAULT_COLUMN_WIDTH; /** * 參數列表 */ protected T parameters; /* (non-Javadoc) * @see com.haier.openplatform.excel.ExcelExportService#doExport(java.io.OutputStream) */ @Override public void doExport(HttpServletResponse response,String fileName) throws IOException { String[] sheetNames = this.getSheetNames(); Validate.notEmpty(sheetNames); this.workbook = new SXSSFWorkbook(getRowAccessWindowSize()); this.titles = this.getTitles(); this.captionRowSytle = crateCaptionCellStyle(); this.titleRowStyle = crateTitleCellStyle(); this.bodyRowStyle = crateBodyCellStyle(); this.afterCreateWorkBook(); for (int i = 0; i < sheetNames.length; i++) { Sheet sheet = workbook.createSheet(sheetNames[i]); this.sheets.add(sheet); afterBuildSheet(i); buildCaption(i); buildTitle(i); afterBuildTitle(i); buildBody(i); afterBuildBody(i); } response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + fileName); OutputStream ouputStream = response.getOutputStream(); workbook.write(ouputStream); ouputStream.flush(); //workbook.close(); ouputStream.close(); } /** * 創建單元格 * @param row * @param index * @param cellValue * @param cellStyle */ protected void createStyledCell(Row row,int index,String cellValue,CellStyle cellStyle){ Cell cell = row.createCell(index); cell.setCellValue(cellValue==null?"":cellValue); cell.setCellStyle(cellStyle); } /** * 創建單元格(數字類型) * @param row * @param index * @param cellValue * @param cellStyle * @throws Exception */ protected <E extends Number> void createNumStyledCell(Row row,int index,E cellValue,CellStyle cellStyle){ Cell cell = row.createCell(index); cell.setCellValue(numParseDouble(cellValue)); cell.setCellStyle(cellStyle); } /** * 數字類型轉double * @param e * @return */ private <E extends Number> Double numParseDouble(E e){ double value=0; if(e!=null){ Method m; try { m = e.getClass().getMethod("doubleValue"); value=(Double)m.invoke(e); } catch (Exception e1) { logger.error(e1.getMessage(),e1); } } return value; } /** * 創建單元格 * @param row * @param index * @param cellValue * @param cellStyle */ protected void createStyledCell(Row row,int index,Double cellValue,CellStyle cellStyle){ Cell cell = row.createCell(index); if(cellValue==null){ cell.setCellValue(""); }else{ cell.setCellValue(cellValue); } cell.setCellStyle(cellStyle); } /** * 創建Integer單元格 * @param row * @param index * @param cellValue * @param cellStyle */ protected void createStyledCell(Row row,int index,Integer cellValue,CellStyle cellStyle){ Cell cell = row.createCell(index); if(cellValue==null){ cell.setCellValue(""); }else{ cell.setCellValue(cellValue); } cell.setCellStyle(cellStyle); } /** * @description 創建double類型單元格 * @author lau * @version 2016-7-13上午11:36:06 * @param */ protected void createStyledCell(Row row,int index,Long cellValue,CellStyle cellStyle){ Cell cell = row.createCell(index); if(cellValue==null){ cell.setCellValue(""); }else{ cell.setCellValue(cellValue); } cell.setCellStyle(cellStyle); } /** * 在創建完畢HSSFWorkBook對象和樣式對象後作的處理操作,通常用來對默認的樣式進行重新定義 */ protected void afterCreateWorkBook(){ } /** * 獲取excel擡頭樣式 * @return */ protected CellStyle crateCaptionCellStyle() { Font font = workbook.createFont(); font.setColor(Font.COLOR_NORMAL); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setWrapText(false); font.setFontHeight((short)250); cellStyle.setFont(font); cellStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.index); cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); return cellStyle; } /** * 獲取excel表頭樣式 * @return */ protected CellStyle crateTitleCellStyle() { Font font = workbook.createFont(); font.setFontHeightInPoints((short) 9);// 字體大小 font.setColor(HSSFColor.WHITE.index);// 字體顏色 font.setFontName("微軟雅黑"); // font.setColor(Font.COLOR_NORMAL); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setWrapText(false); font.setFontHeight((short)250); cellStyle.setFont(font); cellStyle.setFillForegroundColor(HSSFColor.ROYAL_BLUE.index); cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); short border = 1; setCellBorder(cellStyle,border,border,border,border); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return cellStyle; } /** * 設置單元格的border * @param cellStyle * @param top * @param bottom * @param left * @param right */ protected void setCellBorder(CellStyle cellStyle,short top,short bottom,short left,short right){ cellStyle.setBorderBottom(bottom); cellStyle.setBorderLeft(left); cellStyle.setBorderRight(right); cellStyle.setBorderTop(top); } /** * 獲取excel內容樣式 * @return */ protected CellStyle crateBodyCellStyle() { Font font = workbook.createFont(); //font.setColor(HSSFColor.BLUE_GREY.index); font.setFontHeightInPoints((short) 9);// 字體大小 font.setColor(HSSFColor.BLACK.index);// 字體顏色 font.setFontName("微軟雅黑"); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setWrapText(false); cellStyle.setFont(font); cellStyle.setFillForegroundColor(HSSFColor.WHITE.index); cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); cellStyle.setAlignment(CellStyle.ALIGN_LEFT); cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); short border = 1; setCellBorder(cellStyle,border,border,border,border); return cellStyle; } /** * 獲取第n個excel sheet * @param sheetIndex * @return */ protected Sheet getSheet(int sheetIndex) { return this.sheets.get(sheetIndex); } /** * 創建sheet完畢後做的操作 * @param sheetIndex */ protected void afterBuildSheet(int sheetIndex) { } /** * 在sheet的第一行插入標題 * @param sheetIndex */ protected void buildCaption(int sheetIndex){ Sheet sheet = getSheet(sheetIndex); String[] captions = this.getCaptions(); hasCaptionMap.put(sheetIndex, false); if(captions != null && captions.length >=sheetIndex +1){ String caption = captions[sheetIndex]; if(StringUtils.isNotBlank(caption)){ Row row = sheet.createRow(0); int lastColumn = calculateLastColumn(sheetIndex); CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, lastColumn); sheet.addMergedRegion(cellRangeAddress); createStyledCell(row, 0, caption, this.captionRowSytle); hasCaptionMap.put(sheetIndex, true); } } } /** * 計算最後一列數據數據的 * @param sheetIndex * @return */ protected int calculateLastColumn(int sheetIndex){ if(this.titles != null && sheetIndex <= this.titles.length -1 && this.titles[sheetIndex] != null){ return this.titles[sheetIndex].length - 1; }else{ return 1; } } /** * 創建sheet中數據的標題 * @param sheetIndex */ protected void buildTitle(int sheetIndex){ // TODO Auto-generated method stub if(this.titles.length < sheetIndex + 1){ return; } String[] ts = this.titles[sheetIndex]; if(ts == null){ return; } //表頭樣式創建 titleRowStyle=crateTitleCellStyle(); //表頭數填充 Sheet sheet=this.getSheet(sheetIndex); int titleStartRow=this.getTitleStartIndex(sheetIndex); for(int i=titleStartRow;i<this.titles.length+titleStartRow;i++){ Row title=sheet.createRow(i); for(int j=0;j<this.titles[i].length;j++){ sheet.setColumnWidth(j, columnWidth); createStyledCell(title, j, this.titles[i][j], titleRowStyle); } } } /** * 獲取各個sheet內容部分起始行index,默認為從第一行開始 * @param sheetIndex sheet的index * @return */ protected int getBodyStartIndex(int sheetIndex){ int captionRow = getTitleStartIndex(sheetIndex);; int titleRow = 0; if(this.titles != null && this.titles.length >= sheetIndex + 1){ if(titles[sheetIndex] != null && titles[sheetIndex].length >0){ titleRow = 1; } } return captionRow + titleRow; } /** * 獲取各個sheet內容部分起始行index,默認為從第一行開始,支持三行以上動態表頭 * @param sheetIndex sheet的index * @return */ protected int getBodyStartIndex1(int sheetIndex){ int captionRow = getTitleStartIndex(sheetIndex);; int titleRow = 0; if(this.titles != null && this.titles.length >= sheetIndex + 1){ if(titles[sheetIndex] != null && titles.length >0){ titleRow = titles.length; } } return captionRow + titleRow; } protected int getTitleStartIndex(int sheetIndex){ return this.hasCaptionMap.get(sheetIndex) ? 1 : 0; } /** * 創建sheet中數據的標題之後做的操作 * @param sheetIndex */ protected void afterBuildTitle(int sheetIndex) { } /** * 創建sheet中數據的內容 * @param sheetIndex */ protected abstract void buildBody(int sheetIndex); /** * 創建sheet中數據的內容之後做的操作 * @param sheetIndex */ protected void afterBuildBody(int sheetIndex) { } @Override public String[] getCaptions() { return new String[]{}; } @Override public int getRowAccessWindowSize() { return 200; } }

二:繼承模板

  

package com.hailian.util;

import com.hailian.modules.admin.ordermanager.model.CreditOrderInfo;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.ss.usermodel.*;

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



public class AchievementsExport extends SettlrExcelExportTemplate {
    
private List<CreditOrderInfo> list = new ArrayList<CreditOrderInfo>();
    
    public AchievementsExport(List<CreditOrderInfo> list) {
        super();
        this.list = list;
    }

    @Override
    public String[] getSheetNames() {
        return new String[] { "訂單績效" };
    }

    @Override
    public String[][] getTitles() {
        return new String[][] { 
                {"名稱","訂單日期","到期日期","客戶代碼","訂單公司名稱","公司中文名稱","扣分情況","提成"},
        };
    }

    @Override
    public String[] getCaptions() {
        return null;
    }

    @Override
    protected void buildBody(int sheetIndex) {
        
        bodyRowStyle=crateBodyCellStyle();
        bodyRowStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        CellStyle bodyLeftStyle=crateBodyCellStyle();
        CellStyle bodyRightStyle=crateBodyCellStyle();
        bodyRightStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
        bodyLeftStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        bodyRightStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
        
        CellStyle bodyCenterStyle=crateBodyCellStyle();
        bodyCenterStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        
        // 設置為文本格式,防止身份證號變成科學計數法  
        DataFormat format = workbook.createDataFormat();  
        bodyLeftStyle.setDataFormat(format.getFormat("@"));  
        
        Sheet sheet = getSheet(sheetIndex);
        int startIndex = this.getBodyStartIndex(sheetIndex);
//        SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd"); //格式化當前系統日期

        for (int i = 0; i < list.size(); i++) {
            int index = 0;
            Row row1 = sheet.createRow(i + startIndex );
            Cell cell1 = row1.createCell((short) 1);  
            cell1.setCellStyle(bodyLeftStyle);
            row1.setHeight((short) 300);
        CreditOrderInfo searchIndex = list.get(i);
            createStyledCell(row1, index++, searchIndex.get("reportName")==null? "":searchIndex.get("reportName").toString(),bodyRowStyle);
            createStyledCell(row1, index++, searchIndex.get("receiver_date")==null? "":searchIndex.get("receiver_date").toString(),bodyLeftStyle);
            createStyledCell(row1, index++, searchIndex.get("end_date")==null? "":searchIndex.get("end_date").toString(),bodyLeftStyle);
            createStyledCell(row1, index++, searchIndex.get("custom_id")==null? "":searchIndex.get("custom_id").toString(),bodyRowStyle);
            createStyledCell(row1, index++, searchIndex.get("englishName")==null? "":searchIndex.get("englishName").toString(),bodyRowStyle);
            createStyledCell(row1, index++, searchIndex.get("companyName")==null? "":searchIndex.get("companyName").toString(),bodyRowStyle);
            createStyledCell(row1, index++, searchIndex.get("custom_id")==null? "":searchIndex.get("custom_id").toString(),bodyRowStyle);
            createStyledCell(row1, index++, searchIndex.get("custom_id")==null? "":searchIndex.get("custom_id").toString(),bodyRowStyle);
            
        }
        sheet.setColumnWidth(0, 7000);
        sheet.setColumnWidth(1, 3000);
        sheet.setColumnWidth(2, 3000);
        sheet.setColumnWidth(3, 3000);
        sheet.setColumnWidth(4, 3000);
        sheet.setColumnWidth(5, 4000);
        sheet.setColumnWidth(6, 4000);
        sheet.setColumnWidth(7, 4000);
        sheet.setColumnWidth(8, 4000);
        
    
    }

}

三:調用

  

    public void AchievementsExport() {
        String fileName="訂單績效-"+sdf.format(new Date())+".xlsx";
        String time = getPara("time");
        String reportername=getPara("reportername");
        SysUser user= (SysUser) getSessionUser();
        boolean isadmin=isAdmin(user);
        String userid = getSessionUser().getUserid()+"";
        if(isadmin){
            userid="";
        }
        List<CreditOrderInfo> infos  = OrderManagerService.service.exportAchievements(reportername,time,userid,this);
        com.hailian.util.AchievementsExport AchievementsExport=new com.hailian.util.AchievementsExport(infos);
         try {
             fileName=new String(fileName.getBytes("GBK"), "ISO-8859-1");
             AchievementsExport.doExport(getResponse(), fileName);
        renderJson("導出成功");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            renderJson("導出失敗");
        }
    }

註意需要引入相關poi jar包

list集合對象以excel導出