生成excel表格

 單元格節點java

package com.nwvisitor.common.excel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 單元格節點
 */
public class CellNode implements Serializable {

    private static final long serialVersionUID = 8842191357772228473L;
    private String value; // 單元格的內容
    private int col = 1; // 合併幾列
    private int row = 1; // 合併幾行
    private List<CellNode> childNodeList = new ArrayList<CellNode>(); // 下一個單元格節點,合併的單元格的包含多個單元格,不然只有1個單元格
    private CellNode parentNode;
    private String link;//連接
    
    // 樣式相關
    private short color;
    private boolean isTitleCell; //標題設置字體樣式
    
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public int getCol() {
        return col;
    }

    public void setCol(int col) {
        this.col = col;
    }

    public int getRow() {
        return row;
    }

    public void setRow(int row) {
        this.row = row;
    }

    public CellNode getParentNode() {
        return parentNode;
    }

    public void setParentNode(CellNode parentNode) {
        this.parentNode = parentNode;
    }

    public List<CellNode> getChildNodeList() {
        return childNodeList;
    }
    
    public void addChild(CellNode childNode){
        if(childNode != null){
            this.childNodeList.add(childNode);
            childNode.parentNode = this;
        }
    }
    
    public void clearChildren(){
        this.childNodeList.clear();
    }
    
    public void increaseRowOfParent(){
        CellNode parent = this.parentNode;
        while(parent != null){
            parent.increaseRow();
            parent = parent.parentNode;
        }
    }

    public void increaseRow(){
        this.row ++ ;
    }
    
    public void increaseCol(){
        this.col ++;
    }

    public short getColor() {
        return color;
    }

    public void setColor(short color) {
        this.color = color;
    }

    public boolean isTitleCell() {
        return isTitleCell;
    }

    public void setTitleCell(boolean isTitleCell) {
        this.isTitleCell = isTitleCell;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }
    
    /**
     * 獲取N代子節點
     * @param gener 代數,0:表示自身,1表示第一代子節點,以此類推
     * @return
     */
    public CellNode getFirstChildByGener(int gener){
        CellNode node = this;
        for(int i=0;i<gener;i++){
            node = node.getChildNodeList().get(0);
        }
        return node;
    }
}

單元格風格node

package com.alibaba.nwvisitor.common.excel;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;


public class CellStyleUtil {

    public static CellStyle setBorder(CellStyle cellStyle){
        if(cellStyle == null){
            return null;
        }
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);
        cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);
        cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        
        return cellStyle;
    }
    
    public static CellStyle setForeGroundColor(CellStyle cellStyle,short color){
        if(cellStyle == null){
            return null;
        }
        cellStyle.setFillForegroundColor(color);
        cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        return cellStyle;
    }
    
    public static CellStyle setFont(CellStyle cellStyle,Font font){
        if(cellStyle == null || font == null){
            return cellStyle;
        }
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        font.setColor(IndexedColors.BLACK.getIndex());
        font.setFontName("宋體");
        font.setFontHeightInPoints((short)11);
        cellStyle.setFont(font);
        return cellStyle;
    }
    
    public static CellStyle setAlign(CellStyle cellStyle,short align,short vertical){
        if(cellStyle == null){
            return null;
        }
        cellStyle.setAlignment(align);
        cellStyle.setVerticalAlignment(vertical);
        return cellStyle;
    }
    
    
}

建立工做簿apache

package com.alibaba.nwvisitor.common.excel;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;


public class ExcelUtil {

    private static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
    
    private static final String TITLE_STYLE_KEY = "titleStyle";
    private static final String RANGE_STYLE_KEY = "rangeStyle";
    private static final String NORMAL_STYLE_KEY = "normalStyle";
    private static final String SUM_STYLE_KEY = "sumStyle";

    public static Workbook writeToExcel(List<CellNode> nodeList, String sheetName) {
        // 建立一個工做簿
        Workbook wb = new HSSFWorkbook();
        createSheet(wb,nodeList,sheetName);
        return wb;
    }
    
    public static void createSheet(Workbook wb,List<CellNode> nodeList, String sheetName){
        // 建立一個表
        Sheet sheet = wb.createSheet(sheetName);
        Map<String,CellStyle> cellStyleMap = new HashMap<String, CellStyle>();
        if (nodeList != null && nodeList.size() > 0) {
            createRows(sheet, nodeList, 0, 0,cellStyleMap);
        }
        autoSizeColumn(sheet);
    }

    private static void createRows(Sheet sheet, List<CellNode> nodeList, int rowNum, int colNum,Map<String,CellStyle> cellStyleMap) {
        for (CellNode node : nodeList) {
            // 合併單元格
            CellRangeAddress range = null;
            if (node.getCol() > 1 || node.getRow() > 1) {
                range = new CellRangeAddress(rowNum, // first row (0-based)
                        rowNum + node.getRow() - 1, // last row (0-based)
                        colNum, // first column (0-based)
                        colNum + node.getCol() - 1 // last column (0-based)
                );
                sheet.addMergedRegion(range);
            }
            Row row = sheet.getRow(rowNum);
            if (row == null) {
                row = sheet.createRow(rowNum);
            }
            row.setHeightInPoints(18);
            // 設置當前單元格
            Cell cell = row.createCell(colNum, HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(node.getValue());

            // 設置樣式
            setStyle(cell, node, range,cellStyleMap);

            // 建立下一個單元格
            createRows(sheet, node.getChildNodeList(), rowNum, colNum + node.getCol(),cellStyleMap);
            // 建立下一行
            rowNum = rowNum + node.getRow();
        }
    }

    private static void setStyle(Cell cell, CellNode node, CellRangeAddress range,Map<String,CellStyle> cellStyleMap) {
        if (cell == null || node == null || cellStyleMap == null) {
            return;
        }
        CellStyle cellStyle = null;
        // 標題樣式
        if (node.isTitleCell()) {
            cellStyle = getCellStyle(cell.getSheet().getWorkbook(),TITLE_STYLE_KEY,cellStyleMap);
            // 設置背景色
            if (node.getColor() > 0) {
                CellStyleUtil.setForeGroundColor(cellStyle, node.getColor());
            }
            // 設置字體
            CellStyleUtil.setFont(cellStyle, cell.getSheet().getWorkbook().createFont());
        }else if(node.getColor() > 0){
            cellStyle = getCellStyle(cell.getSheet().getWorkbook(),SUM_STYLE_KEY,cellStyleMap);
            CellStyleUtil.setForeGroundColor(cellStyle, node.getColor());
        }else if(range != null) {
            cellStyle = getCellStyle(cell.getSheet().getWorkbook(),RANGE_STYLE_KEY,cellStyleMap);
            CellStyleUtil.setAlign(cellStyle, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_CENTER);
            setRegionStyle(cell.getSheet(), range, cellStyle);
        }else{
            cellStyle = getCellStyle(cell.getSheet().getWorkbook(),NORMAL_STYLE_KEY,cellStyleMap);
        }
        // 設置邊框
        CellStyleUtil.setBorder(cellStyle);

        // 設置居中,合併的單元格居中
        CellStyleUtil.setAlign(cellStyle, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_CENTER);
        
        cell.setCellStyle(cellStyle);
    }
    
    private static CellStyle getCellStyle(Workbook wb ,String key,Map<String,CellStyle> cellStyleMap){
        CellStyle cellStyle = cellStyleMap.get(key);
        if(cellStyle == null){
            cellStyle = wb.createCellStyle();
            cellStyleMap.put(key,cellStyle);
        }
        return cellStyle;
    }

    // 設置被合併的單元格的樣式
    private static void setRegionStyle(Sheet sheet, CellRangeAddress region, CellStyle cellStyle) {
        if(sheet == null || region == null || cellStyle == null){
            return;
        }
        for (int i = region.getFirstRow(); i <= region.getLastRow(); i++) {
            Row row = CellUtil.getRow(i, sheet);
            for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
                Cell cell = CellUtil.getCell(row, j);
                cell.setCellStyle(cellStyle);
            }
        }
    }
    
    // POI的自適應對中文有bug,使用設置列的寬度
    private static void autoSizeColumn(Sheet sheet){
        if(sheet == null){
            return ;
        }
        Map<Integer,Integer> maxColumnSizeMap = new HashMap<Integer, Integer>();
        int maxColNum = 0;
        Iterator<Row> rowIt = sheet.rowIterator();
        while(rowIt.hasNext()){
            Row row = rowIt.next();
            Iterator<Cell> cellIt = row.cellIterator();
            int colIndex = 0;
            while(cellIt.hasNext()){
                Cell cell = cellIt.next();
                String value = cell.getStringCellValue();
                int length = value == null ? 0 : value.getBytes().length;
                int maxLen = maxColumnSizeMap.get(colIndex) == null ? 0 : maxColumnSizeMap.get(colIndex);
                maxLen = maxLen < length ? length : maxLen;
                maxColumnSizeMap.put(colIndex, maxLen);
                colIndex ++ ;
            }
            maxColNum = maxColNum < colIndex ? colIndex : maxColNum;
        }
        
        for(int i=0;i<maxColNum;i++){
            int maxLen = maxColumnSizeMap.get(i) == null ? 0 : maxColumnSizeMap.get(i);
            if(maxLen > 0){
                sheet.setColumnWidth(i,maxLen*256);
            }
        }
        
        /*Row row = sheet.getRow(0);
        if(row == null){
            return ;
        }
        Iterator<Cell> cellIt = row.cellIterator();
        while(cellIt.hasNext()){
            Cell cell = cellIt.next();
            sheet.autoSizeColumn(cell.getColumnIndex());
        }*/
    }

    public static void writeToFile(List<CellNode> nodeList, String sheetName, String fileName) {
        // 將工做簿輸出到文件
        FileOutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream(fileName);
            Workbook wb = writeToExcel(nodeList, sheetName);
            wb.write(fileOut);
            fileOut.close();
        } catch (Exception e) {
            logger.error("write to excel file error!", e);
        } finally {
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                    logger.error("close FileOutputStream error !", e);
                }
            }
        }
    }

    
    public static List<List<CellNode>> toCellNodeList(List<CellNode> nodeList){
        List<List<CellNode>> resultList = new ArrayList<List<CellNode>>();
        if(nodeList == null || nodeList.size() == 0){
            return resultList;
        }
        createListRows(resultList,nodeList,0);
        return resultList;
    }
    
    private static void createListRows(List<List<CellNode>> resultList, List<CellNode> nodeList, int rowNum) {
        for (CellNode node : nodeList) {
            List<CellNode> oneList = new ArrayList<CellNode>();
            if(resultList.size() > rowNum){
                oneList = resultList.get(rowNum);
            }else{
                resultList.add(oneList);
            }
            oneList.add(node);

            // 建立下一個單元格
            createListRows(resultList, node.getChildNodeList(), rowNum);
            // 建立下一行
            rowNum = rowNum + node.getRow();
        }
    }
}
相關文章
相關標籤/搜索