PoiUtil.java 用於excel間sheet複製

前言:apache提供的poi功能確實比較強大,可是不明白爲何沒有相應的方法實現不一樣excel文件中sheet的複製功能。這也是本文整理PoiUtil工具類的初衷。網上有相關的解決方案,在參考了網上諸多的解決方案、示例代碼以後,就有了該工具類,特別感謝各位前輩,讓我可以站在巨人的肩膀上,用拳頭摳摳鼻屎。廢話很少說了,下面是PoiUtil工具類的源碼: java

package com.poi.extend;

import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;

/**
 * POI工具類 功能點: 
 * 一、實現excel的sheet複製,複製的內容包括單元的內容、樣式、註釋
 * 二、setMForeColor修改HSSFColor.YELLOW的色值,setMBorderColor修改PINK的色值
 * 
 * @author Administrator
 */
public final class PoiUtil {

	/**
	 * 功能:拷貝sheet
	 * 實際調用 	copySheet(targetSheet, sourceSheet, targetWork, sourceWork, true)
	 * @param targetSheet
	 * @param sourceSheet
	 * @param targetWork
	 * @param sourceWork                                                                   
	 */
	public static void copySheet(HSSFSheet targetSheet, HSSFSheet sourceSheet,
			HSSFWorkbook targetWork, HSSFWorkbook sourceWork) throws Exception{
		if(targetSheet == null || sourceSheet == null || targetWork == null || sourceWork == null){
			throw new IllegalArgumentException("調用PoiUtil.copySheet()方法時,targetSheet、sourceSheet、targetWork、sourceWork都不能爲空,故拋出該異常!");
		}
		copySheet(targetSheet, sourceSheet, targetWork, sourceWork, true);
	}

	/**
	 * 功能:拷貝sheet
	 * @param targetSheet
	 * @param sourceSheet
	 * @param targetWork
	 * @param sourceWork
	 * @param copyStyle					boolean 是否拷貝樣式
	 */
	public static void copySheet(HSSFSheet targetSheet, HSSFSheet sourceSheet,
			HSSFWorkbook targetWork, HSSFWorkbook sourceWork, boolean copyStyle)throws Exception {
		
		if(targetSheet == null || sourceSheet == null || targetWork == null || sourceWork == null){
			throw new IllegalArgumentException("調用PoiUtil.copySheet()方法時,targetSheet、sourceSheet、targetWork、sourceWork都不能爲空,故拋出該異常!");
		}
		
		//複製源表中的行
		int maxColumnNum = 0;

		Map styleMap = (copyStyle) ? new HashMap() : null;
		
		HSSFPatriarch patriarch = targetSheet.createDrawingPatriarch(); //用於複製註釋
		for (int i = sourceSheet.getFirstRowNum(); i <= sourceSheet.getLastRowNum(); i++) {
			HSSFRow sourceRow = sourceSheet.getRow(i);
			HSSFRow targetRow = targetSheet.createRow(i);
			
			if (sourceRow != null) {
				copyRow(targetRow, sourceRow,
						targetWork, sourceWork,patriarch, styleMap);
				if (sourceRow.getLastCellNum() > maxColumnNum) {
					maxColumnNum = sourceRow.getLastCellNum();
				}
			}
		}
		
		//複製源表中的合併單元格
		mergerRegion(targetSheet, sourceSheet);
		
		//設置目標sheet的列寬
		for (int i = 0; i <= maxColumnNum; i++) {
			targetSheet.setColumnWidth(i, sourceSheet.getColumnWidth(i));
		}
	}
	
	/**
	 * 功能:拷貝row
	 * @param targetRow
	 * @param sourceRow
	 * @param styleMap
	 * @param targetWork
	 * @param sourceWork
	 * @param targetPatriarch
	 */
	public static void copyRow(HSSFRow targetRow, HSSFRow sourceRow,
			HSSFWorkbook targetWork, HSSFWorkbook sourceWork,HSSFPatriarch targetPatriarch, Map styleMap) throws Exception {
		if(targetRow == null || sourceRow == null || targetWork == null || sourceWork == null || targetPatriarch == null){
			throw new IllegalArgumentException("調用PoiUtil.copyRow()方法時,targetRow、sourceRow、targetWork、sourceWork、targetPatriarch都不能爲空,故拋出該異常!");
		}
		
		//設置行高
		targetRow.setHeight(sourceRow.getHeight());
		
		for (int i = sourceRow.getFirstCellNum(); i <= sourceRow.getLastCellNum(); i++) {
			HSSFCell sourceCell = sourceRow.getCell(i);
			HSSFCell targetCell = targetRow.getCell(i);
			
			if (sourceCell != null) {
				if (targetCell == null) {
					targetCell = targetRow.createCell(i);
				}
				
				//拷貝單元格,包括內容和樣式
				copyCell(targetCell, sourceCell, targetWork, sourceWork, styleMap);
				
				//拷貝單元格註釋
				copyComment(targetCell,sourceCell,targetPatriarch);
			}
		}
	}
	
	/**
	 * 功能:拷貝cell,依據styleMap是否爲空判斷是否拷貝單元格樣式
	 * @param targetCell			不能爲空
	 * @param sourceCell			不能爲空
	 * @param targetWork			不能爲空
	 * @param sourceWork			不能爲空
	 * @param styleMap				能夠爲空				
	 */
	public static void copyCell(HSSFCell targetCell, HSSFCell sourceCell, HSSFWorkbook targetWork, HSSFWorkbook sourceWork,Map styleMap) {
		if(targetCell == null || sourceCell == null || targetWork == null || sourceWork == null ){
			throw new IllegalArgumentException("調用PoiUtil.copyCell()方法時,targetCell、sourceCell、targetWork、sourceWork都不能爲空,故拋出該異常!");
		}
		
		//處理單元格樣式
		if(styleMap != null){
			if (targetWork == sourceWork) {
				targetCell.setCellStyle(sourceCell.getCellStyle());
			} else {
				String stHashCode = "" + sourceCell.getCellStyle().hashCode();
				HSSFCellStyle targetCellStyle = (HSSFCellStyle) styleMap
						.get(stHashCode);
				if (targetCellStyle == null) {
					targetCellStyle = targetWork.createCellStyle();
					targetCellStyle.cloneStyleFrom(sourceCell.getCellStyle());
					styleMap.put(stHashCode, targetCellStyle);
				}
				
				targetCell.setCellStyle(targetCellStyle);
			}
		}
		
		//處理單元格內容
		switch (sourceCell.getCellType()) {
		case HSSFCell.CELL_TYPE_STRING:
			targetCell.setCellValue(sourceCell.getRichStringCellValue());
			break;
		case HSSFCell.CELL_TYPE_NUMERIC:
			targetCell.setCellValue(sourceCell.getNumericCellValue());
			break;
		case HSSFCell.CELL_TYPE_BLANK:
			targetCell.setCellType(HSSFCell.CELL_TYPE_BLANK);
			break;
		case HSSFCell.CELL_TYPE_BOOLEAN:
			targetCell.setCellValue(sourceCell.getBooleanCellValue());
			break;
		case HSSFCell.CELL_TYPE_ERROR:
			targetCell.setCellErrorValue(sourceCell.getErrorCellValue());
			break;
		case HSSFCell.CELL_TYPE_FORMULA:
			targetCell.setCellFormula(sourceCell.getCellFormula());
			break;
		default:
			break;
		}
	}
	
	/**
	 * 功能:拷貝comment
	 * @param targetCell
	 * @param sourceCell
	 * @param targetPatriarch
	 */
	public static void copyComment(HSSFCell targetCell,HSSFCell sourceCell,HSSFPatriarch targetPatriarch)throws Exception{
		if(targetCell == null || sourceCell == null || targetPatriarch == null){
			throw new IllegalArgumentException("調用PoiUtil.copyCommentr()方法時,targetCell、sourceCell、targetPatriarch都不能爲空,故拋出該異常!");
		}
		
		//處理單元格註釋
		HSSFComment comment = sourceCell.getCellComment();
		if(comment != null){
			HSSFComment newComment = targetPatriarch.createComment(new HSSFClientAnchor());
			newComment.setAuthor(comment.getAuthor());
			newComment.setColumn(comment.getColumn());
			newComment.setFillColor(comment.getFillColor());
			newComment.setHorizontalAlignment(comment.getHorizontalAlignment());
			newComment.setLineStyle(comment.getLineStyle());
			newComment.setLineStyleColor(comment.getLineStyleColor());
			newComment.setLineWidth(comment.getLineWidth());
			newComment.setMarginBottom(comment.getMarginBottom());
			newComment.setMarginLeft(comment.getMarginLeft());
			newComment.setMarginTop(comment.getMarginTop());
			newComment.setMarginRight(comment.getMarginRight());
			newComment.setNoFill(comment.isNoFill());
			newComment.setRow(comment.getRow());
			newComment.setShapeType(comment.getShapeType());
			newComment.setString(comment.getString());
			newComment.setVerticalAlignment(comment.getVerticalAlignment());
			newComment.setVisible(comment.isVisible());
			targetCell.setCellComment(newComment);
		}
	}
	
	/**
	 * 功能:複製原有sheet的合併單元格到新建立的sheet
	 * 
	 * @param sheetCreat
	 * @param sourceSheet
	 */
	public static void mergerRegion(HSSFSheet targetSheet, HSSFSheet sourceSheet)throws Exception {
		if(targetSheet == null || sourceSheet == null){
			throw new IllegalArgumentException("調用PoiUtil.mergerRegion()方法時,targetSheet或者sourceSheet不能爲空,故拋出該異常!");
		}
		
		for (int i = 0; i < sourceSheet.getNumMergedRegions(); i++) {
			CellRangeAddress oldRange = sourceSheet.getMergedRegion(i);
			CellRangeAddress newRange = new CellRangeAddress(
					oldRange.getFirstRow(), oldRange.getLastRow(),
					oldRange.getFirstColumn(), oldRange.getLastColumn());
			targetSheet.addMergedRegion(newRange);
		}
	}

	/**
	 * 功能:從新定義HSSFColor.YELLOW的色值
	 * 
	 * @param workbook
	 * @return
	 */
	public static HSSFColor setMForeColor(HSSFWorkbook workbook) {
		HSSFPalette palette = workbook.getCustomPalette();
		HSSFColor hssfColor = null;
		// byte[] rgb = { (byte) 221, (byte) 241, (byte) 255 };
		// try {
			// hssfColor = palette.findColor(rgb[0], rgb[1], rgb[2]);
			// if (hssfColor == null) {
				// palette.setColorAtIndex(HSSFColor.YELLOW.index, rgb[0], rgb[1],
						// rgb[2]);
				// hssfColor = palette.getColor(HSSFColor.YELLOW.index);
			// }
		// } catch (Exception e) {
			// e.printStackTrace();
		// }
		// return hssfColor;
	// }
	/**
	 * 功能:從新定義HSSFColor.PINK的色值
	 * 
	 * @param workbook
	 * @return
	 */
	public static HSSFColor setMBorderColor(HSSFWorkbook workbook) {
		HSSFPalette palette = workbook.getCustomPalette();
		HSSFColor hssfColor = null;
		byte[] rgb = { (byte) 0, (byte) 128, (byte) 192 };
		try {
			hssfColor = palette.findColor(rgb[0], rgb[1], rgb[2]);
			if (hssfColor == null) {
				palette.setColorAtIndex(HSSFColor.PINK.index, rgb[0], rgb[1],
						rgb[2]);
				hssfColor = palette.getColor(HSSFColor.PINK.index);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hssfColor;
	}
}

關於工具類的使用,能夠簡單的調用copySheet方法完成sheet的複製。 apache

注意:整理該工具類用到的poi版本是 3.2-FINAL-20081019,jdk的版本是1.4 工具

相關文章
相關標籤/搜索